[LeetCode]45. Jump Game II

最少的步数

Posted by JinFei on March 26, 2020

题目描述

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example1:

  Input: [2,3,1,1,4]
    Output: 2
    Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

解题思路

  • 致谢!参考
  • 感觉是贪心的一种做法
  • 为了较快的跳到末尾,想知道每一步能跳的范围,这里贪婪并不是要在能跳的范围中选跳力最远的那个位置,因为这样选下来不一定是最优解,这么一说感觉又有点不像贪婪算法了。
  • 其实这里贪的是一个能到达的最远范围,遍历当前跳跃能到的所有位置,然后根据该位置上的跳力来预测下一步能跳到的最远距离,贪出一个最远的范围,一旦当这个范围到达末尾时,当前所用的步数一定是最小步数。
  • 需要两个变量 cur 和 pre 分别来保存当前的能到达的最远位置和之前能到达的最远位置,只要 cur 未达到最后一个位置则循环继续,pre 先赋值为 cur 的值,表示上一次循环后能到达的最远位置,如果当前位置i小于等于 pre,说明还是在上一跳能到达的范围内,根据当前位置加跳力来更新 cur,更新 cur 的方法是比较当前的 cur 和 i + A[i] 之中的较大值
class Solution {
public:
    int jump(vector<int>& nums) {
        int i = 0;
        int cur = 0;
        int res = 0;
        while(cur < nums.size() - 1){
            res++;
            int pre = cur;
            for(; i <= pre; i++){
                cur = max(cur, i + nums[i]);
            }
        }
        return res;
    }
};