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;
}
};