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
.
class Solution
{
public:
bool canJump(int A[], int n) {
int reach = 0; //the rightmost reachable position
for(int i=0; i<=reach && reach<n-1; i++)
reach = max(reach, i+A[i]);
return reach >= n-1;
}
};
思路2:动态规划。参考 http://fisherlei.blogspot.hk/2012/12/leetcode-jump-game.html
class Solution
{
public:
bool canJump(int A[], int n) {
vector<int> f(n, 0);
f[0] = 0;
for(int i=1; i<n; ++i)
{
f[i] = max(f[i-1], A[i-1]) -1;
if(f[i] < 0) return false;
}
return true;
}
};