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.
Method1. DP
class Solution {
public boolean canJump(int[] nums) {
boolean[] dp = new boolean[nums.length];
dp[nums.length - 1] = true;
for(int i = nums.length - 2; i >= 0; i--) {
for(int j = i + 1; j <= i + nums[i]; j++) {
if(dp[j] && i-j <= nums[j]) {
dp[i] = true;
break;
}
}
}
return dp[0];
}
}
Method 2. Greedy
class Solution {
public boolean canJump(int[] nums) {
if (nums == null || nums.length == 0) {
return false;
}
int farthest = nums[0];
for (int i = 1; i < nums.length; i++) {
if (i <= farthest && nums[i] + i >= farthest) {
farthest = nums[i] + i;
}
}
return farthest >= nums.length - 1;
}
}