leetcode#45. Jump Game II
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
说明:
假设你总是可以到达数组的最后一个位置。
dfs和dp都超时。。。
class Solution { public: //有点像bfs,每一次跳跃会有个可到达范围(index),我们遍历整个index //可以得到下一次能到达的最大范围。 int jump(vector<int>& nums) { int res = 0; int n = nums.size(); int pos_pre = 0, pos_now = 0; while (pos_now < n - 1) { int start=pos_pre; pos_pre = pos_now;//记录当前位置 while (start <= pos_pre)//上一次的点到当前位置所有的点 { pos_now = max(pos_now, start + nums[start]);//选择那个跳得最远的点 start++; } if (pos_pre == pos_now) return -1; // May not need this ++res;//跳一次 } return res; } };

浙公网安备 33010602011771号