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]
, return true
.
A = [3,2,1,0,4]
, return false
.
[Analysis]
动态规划问题。使用bool dp[1:n]数组,dp[i]表示从A[i]可以跳到A[n],从n-1~1更新数组。
对于dp[i],令step = 1~A[i],只要存在一个step,使得dp[i+step]=true,则dp[i]=true。
step可以从1~A[i]按step++的方式递增,但是这样在Large Judge时会TLE,更好的方法是:
如果dp[i+step]=false,即从i跳一个长度为step的一跳后,仍然无法从A[i+step]跳到A[n],那么直接从A[i+step]能够到达最远的地方的后面一位开始跳,即step += A[i+step] + 1。
[Solution]
class Solution {
public:
bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 0)return true;
bool mark[n];
memset(mark, false, sizeof(mark));
mark[n-1] = true;
for(int i = n-2; i >= 0; --i){
int j = 1;
while(j <= A[i]){
if(i + j == n - 1){
mark[i] = true;
break;
}
else if(i + j > n - 1){
break;
}
else{
mark[i] = mark[i+j];
if(mark[i] == true){
break;
}
}
j += A[i+j] + 1;
}
}
return mark[0];
}
};
说明:版权所有,转载请注明出处。 Coder007的博客