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.
Example
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
public class Solution {
/**
* @param A: A list of integers
* @return: The boolean answer
*/
public boolean canJump(int[] A) {
if(A.length == 0) return true;
int i = A[0], j = 1;
while(i > 0 && j < A.length) {
i = Math.max(i, A[j]);
j++;
i--;
}
return j == A.length;
}
}
一维DP的话,res[i]代表是否能到达第i个位置。 针对每个位置,向前遍历,查看前面所有点是否能到达该位置。
public class Solution {
/**
* @param A: A list of integers
* @return: The boolean answer
*/
public boolean canJump(int[] A) {
if(A.length == 0) return true;
boolean[] res = new boolean[A.length];
res[0] = true;
for(int i = 1; i < A.length; i++) {
for(int j = i - 1; j >= 0; j--) {
if(res[j] && A[j] + j >= i) {
res[i] = true;
break;
}
}
}
return res[A.length - 1];
}
}