jump-game

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.
Determine if you are able to reach the last index.
For example:
A =[2,3,1,1,4], returntrue.
A =[3,2,1,0,4], returnfalse.

开始想的是对于在i点时,跳过A[i]步,但是这有一个问题就是它给出的值是可以跳过的最大值,比如[3,3,2,0,1]这种,开始的想法就会出错。

方法Ⅰ
思路:动态规划。初始第一个index为true,其他全部为false;如果当前index为true则把从当前开始到后面的A[i]个位置都变成true.最后一个index如果为true就说明可以到达。

代码:

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

方法Ⅱ
思路:同样是动态规划,方法可以延伸到jump-game-ii上

我们维护一个一位数组dp,其中dp[i]表示走到第i位剩余的最大步数,于是可得dp[i] = max(dp[i - 1], A[i - 1]) - 1,如果当某一个时刻dp数组的值为负了,说明无法抵达当前位置,则直接返回false,最后我们判断dp数组最后一位是否为非负数即可知道是否能抵达该位置。

代码:

class Solution {
public:
    bool canJump(int A[], int n) {
        if(n <= 0)
            return false;
        vector<int> dp(n,0);
        for(int i = 1;i < n;++i){
            dp[i] = max(dp[i-1],A[i-1]) - 1;
            if(dp[i] < 0)//这里不能用<=,因为最后一步是可以等于0的
                return false;
        }
        return dp[n-1]>=0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值