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.
java code : 这题初看用DP的思路很清晰: 设DP[i] := 从第 i 个位置开始能否到底最后一个位置,那么转移方程很好写
dp[A.length - 1] = true; 看代码吧,不过会超时,因为复杂度是O(n^2)
[java]
public boolean canJump(int[] A)
{
if(A.length <= 1)
return true;
if(A[0] >= (A.length - 1))
return true;
boolean[] dp = new boolean[A.length];
dp[A.length - 1] = true;
for(int i = A.length - 2; i >= 0; i--)
{
if(i + A[i] >= A.length - 1)
{
dp[i] = true;
continue;
}
for(int j = i + 1; j < A.length - 1; j++)
{
if(i + A[i] >= j)
{
dp[i] |= dp[j];
if(dp[i] == true)
break;
}
}
}
boolean res = false;
if(dp[0] == true)
res = true;
dp = null;
return res;
}
下面给出一种O(n)的算法:
我们用maxlength 维护一个从开始位置能到达的最远距离,然后判断在当前位置是否能够到底最后一个位置和当前位置是否可达,如果两个条件都满足,那么返回true,如果当前位置是0,并且最远距离不能超过当前位置,那么只能返回false 了,更新最远距离
java code : 416ms
[java]
public class Solution {
public boolean canJump(int[] A) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(A.length <= 1)
return true;
if(A[0] >= (A.length - 1))
return true;
int maxlength = A[0];
if(maxlength == 0)
return false;
for(int i = 1; i < A.length - 1; i++)
{
if(maxlength >= i && (i + A[i]) >= A.length - 1)
return true;
if(maxlength <= i && A[i] == 0)
return false;
if((i + A[i]) > maxlength)
maxlength = i + A[i];
}
return false;
}
}
顺便说一下我看讨论区有人贴出如此算法并且还过了:
[cpp]
class Solution {
public:
bool canJump(int A[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int i = 0;
while( i < n-1)
{
if( A[i] == 0)
return false;
i += A[i];
}
return i >= n-1;
}
};
这个算法是错误的,因为有一组反列: A = {5,4,0,0,0,0,0}, 显然应该返回 false.
leetcode 的数据还是有点弱。