原题网址:https://leetcode.com/problems/jump-game/
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.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
方法一:动态规划。
public class Solution {
public boolean canJump(int[] nums) {
boolean[] reach = new boolean[nums.length];
reach[0] = true;
int far = 0;
for(int i=0; i<nums.length-1; i++) {
if (!reach[i]) continue;
for(int j=far+1; j<= Math.min(nums.length-1, i+nums[i]); j++) {
reach[j] = true;
if (j==nums.length-1) return true;
}
far = Math.min(nums.length-1, i+nums[i]);
}
return reach[nums.length-1];
}
}
方法二:动态规划,优化内存。
public class Solution {
public boolean canJump(int[] nums) {
int far = 0;
for(int i=0; i<nums.length; i++) {
if (far < i) return false;
far = Math.max(far, i+nums[i]);
}
return true;
}
}