[LeetCode] Jump Game II

Jump Game II

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.

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

解题思路:

最值问题,第一想到的就是动态规划。用d[i]记录从0到i最小的步数,则d[i]=min(d[k]+1),其中k是所有能够到达i的下标。最开始,我用一个vector数组记录所有能够到达自身的下标,代码如下:

class Solution {
public:
    int jump(vector<int>& nums) {
        int len = nums.size();
        if(len<2){
            return 0;
        }
        int d[len];
        d[0] = 0;
        vector<int> pre[len];
        for(int i=1; i<=nums[0] && i<len; i++){
            pre[i].push_back(0);
        }
        for(int i=1; i<len; i++){
            d[i] = INT_MAX;
            for(int j=0; j<pre[i].size(); j++){
                d[i] = min(d[i], d[pre[i][j]] + 1);
            }
            for(int j=i+1; j<=(nums[i] + i) && j<len; j++){
                pre[j].push_back(i);
            }
        }
        return d[len-1];
    }
};

时间复杂度为O(n*n),空间复杂度为O(n*n)。超时错误。

后经过改进,不需要记录前驱节点,代码如下,空间复杂度变为O(n),但时间复杂度仍为O(n*n),产生超时错误。

class Solution {
public:
    int jump(vector<int>& nums) {
        int len = nums.size();
        if(len<2){
            return 0;
        }
        int d[len];
        for(int i=1; i<len; i++){
            d[i] = INT_MAX;
        }
        d[0] = 0;
        for(int i=0; i<len; i++){
            for(int j=i+1; j<=(nums[i]+i) && j<len; j++){
                d[j]=min(d[j], d[i] + 1);
            }
        }
        return d[len-1];
    }
};

水中的<。)#)))≦给我们一个非常好的解法:http://fisherlei.blogspot.com/2012/12/leetcode-jump-ii.html,采用贪心算法,记录第k步最多能够走,且对第k+1步有影响的范围[Left, Right],每走一步,left变成right+1,right变成[left, right]区间内走一步最远的下标。这里与上述方法的根本区别就是left=right+1,而非left=left+1,这样能够减少很多计算。因为[left+1, right]已经在[left, right]时已经计算过了。

class Solution {
public:
    int jump(vector<int>& nums) {
        int len = nums.size();
        int left = 0;
        int right = 0;
        int count = 0;
        while(right<len-1){
            count++;
            int mostRight = right;
            for(int i=left; i<=right; i++){
                mostRight = max(mostRight, i+nums[i]);
                if(mostRight>=len - 1){
                    break;
                }
            }
            left = right + 1;
            right=mostRight;
            if(right<left){
                return -1;
            }
        }
        
        return count;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注