leetcode 55. Jump Game、45. Jump Game II(贪心)

55. Jump Game

第一种方法:

只要找到一个方式可以到达,那当前位置就是可以到达的,所以可以break

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int length = nums.size();
        if(length <= 0)
            return false;
        vector<bool> dp(length,false);
        dp[0] = true;
        for(int i = 1;i < length;i++){
            for(int j = i - 1;j >= 0;j--){
                if(dp[j] == true && i - j <= nums[j]){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[length-1];
    }
};

第二种方法:

第一种方法时间复杂度高且需要O(n)的空间复杂度。这题用贪心在O(n)的时间复杂度,O(1)的空间复杂度就可以解决。

用一个reach变量记录当前位置能达到的最远的位置索引,每次更新,如果reach比当前的索引小伙子reach已经能到达最后一个位置就可以break掉。

注意:reach及其比较的对象都是数组的索引,即n-1。

https://www.cnblogs.com/grandyang/p/4371526.html

class Solution {
public:
    bool canJump(vector<int>& nums) {
        if(nums.empty())
            return false;
        int reach = 0;
        for(int i = 0;i < nums.size();i++){
            if(reach < i || reach >= nums.size() - 1)
                break;
            reach = max(reach,i + nums[i]);
        }
        return reach >= nums.size() - 1;
    }
};

 

45. Jump Game II

https://www.cnblogs.com/grandyang/p/4373533.html

pre记录的是前一次能达到的最远位置的索引,cur是当前能达到的最远位置的索引。

你每一次的更新其实都是在前一次最远距离的范围内更新下一次的最远距离。

这个i是当前遍历的位置。

class Solution {
public:
    int jump(vector<int>& nums) {
        int cur = 0,res = 0,i = 0;
        int pre;
        while(cur < nums.size() - 1){
            res++;
            pre = cur;
            for(;i <= pre;i++)
                cur = max(cur,i + nums[i]);
        }
        return res;
    }
};

 

posted @ 2019-04-15 11:55  有梦就要去实现他  阅读(133)  评论(0编辑  收藏  举报