【Leetcode】45. Jump Game II

来源:互联网 发布:阿里云服务器挂载 编辑:程序博客网 时间:2024/05/18 10:21

Description:

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.

Note:

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

Example:

Given array A = [2,3,1,1,4]

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.)


思路:

对于本题而言,与之前的Jump Game不同,Jump Game II是求到达最后一个位置所需的最少步数。另外,这里提到所给的数组是一定可以到达最后位置,所以不必作可行性判断。接上一次Jump Game的思考,每次选取当前位置能到达的最远位置作为下一个位置(next)不一定意味着达到终点步数最少。不过这一点具有参考意义,也就是说当前位置(pos)与当前位置所能到达的最远位置或称为结束位置(end)之间的任一点所能到达的最远位置的最大值可以作为下一个位置(next),下一个位置又将作为下一步的结束位置,这样可以保证最少的步骤到达终点。这是因为当前位置(pos)与当前位置所能到达的最远位置或称为结束位置(end)之间的任一点是当前位置只需要一步就能到达的,那么从这里面的任一点到下一个点也只需一步,通过这样的贪心算法可以安全地选择到这段距离内的最远位置。

以下是使用C++实现的过程:

class Solution {public:    int jump(vector<int>& nums) {        int jumps = 0;        int end = 0, next = 0;        for (int pos=0; pos<nums.size()-1; pos++) {            if(pos+nums[pos]>next)                next = pos+nums[pos];            if (pos == end) {                jumps++;                end = next;            }        }        return jumps;    }};
0 0