code1:贪心算法
//从右向左迭代,对于每个节点我们检查是否存在一步跳跃可以到达 GOOD 的位置
//(currPosition + nums[currPosition] >= leftmostGoodIndex)。
//如果可以到达,当前位置也标记为 GOOD ,同时,这个位置将成为新的最左边的 GOOD 位置,
//一直重复到数组的开头,如果第一个坐标标记为 GOOD 意味着可以从第一个位置跳到最后的位置。
public 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;
}
}
//贪心算法的第二种形式
public boolean canJump(int[] nums) {
int n=nums.length;
int reach=0;
for(int i=0;i<n;i++){
if( i> reach || reach>=n-1)
break;
reach=Math.max(reach,i+nums[i]);
}
return reach>=n-1;
}
code2:动态规划算法
class Solution {
public boolean canJump(int[] nums) {
if (nums == null) {
return false;
}
boolean[] dp = new boolean[nums.length];
dp[0] = true;
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
// 如果之前的j节点可达,并且从此节点可以到跳到i
if (dp[j] && nums[j] + j >= i) {
dp[i] = true;
break;
}
}
}
return dp[nums.length - 1];
}
}
code3:
//判断是否存在0,存在则--我们判断 0 前边的元素能否跳过 0 ,
//不需要每次都向前查找,我们只需要用一个变量保存当前能跳的最远的距离,
//然后判断最远距离和当前 0 的位置就可以了
public boolean canJump(int[] nums) {
int max = 0;
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 0 && i >= max) {
return false;
}
max = Math.max(max, nums[i] + i);
}
return true;
}
code4:
//改进上面算法,进一步优化为,最大距离是否超过当前的i
public boolean canJump(int[] nums) {
int max = 0;
for (int i = 0; i < nums.length; i++) {
if (i > max) {
return false;
}
max = Math.max(max, nums[i] + i);
}
return true;
}