题目描述:给定一个数组,从index为0开始,每次最大可以跳nums[index]步,能跳到index为length-1为true,不能则为false。
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
方法一:贪心算法,不断更新lastPos,判断当前点能否跳到lastPos,能跳到则将当前点设置为lastPos,直到lastPos为0则返回true,lastPos不为0则返回false。
class Solution {
public boolean canJump(int[] nums) {
int lastPos = nums.length - 1;
for(int i = nums.length - 1; i >= 0;i--){
if(i + nums[i] >= lastPos){
lastPos = i;
}
}
return lastPos == 0;
}
}
方法二:动态规划,自顶向下,为每个节点设置一个状态
enum Index {
GOOD, BAD, UNKNOWN
}
public class JumpGame {
Index[] dp;
public boolean canJumpWithIndex(int[] nums, int index) {
if (dp[index] != Index.UNKNOWN) {
return dp[index] == Index.GOOD;
}
//此点最远可跳的距离
int furthestIndex = Math.min(index + nums[index], nums.length - 1);
//从第一步一直到最后一步,判断可否跳到最后一个点
for(int i = index + 1;i <= furthestIndex;i++){
if(canJumpWithIndex(nums,i)){
dp[index] = Index.GOOD;
return true;
}
}
dp[index] = Index.BAD;
return false;
}
public boolean canJump(int[] nums) {
dp = new Index[nums.length];
for (int i = 0; i < dp.length; i++) {
dp[i] = Index.UNKNOWN;
}
//自己本身是可以跳到自己本身的,所以将最后一个点设置为good
dp[dp.length - 1] = Index.GOOD;
return canJumpWithIndex(nums, 0);
}
}
方法三:动态规划,自底向上
enum Index {
GOOD, BAD, UNKNOWN
}
class Solution {
public boolean canJump(int[] nums) {
Index[] dp = new Index[nums.length];
dp = new Index[nums.length];
for (int i = 0; i < dp.length; i++) {
dp[i] = Index.UNKNOWN;
}
dp[dp.length - 1] = Index.GOOD;
for(int i = nums.length - 2;i >=0 ;i--){
int furthestIndex = Math.min(i + nums[i], nums.length - 1);
for(int j = i;j <= furthestIndex;j++){
if (dp[j] == Index.GOOD){
dp[i] = Index.GOOD;
break;
}
}
}
return dp[0] == Index.GOOD;
}
}