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 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
tag: array,greedy, dynamic programming
method 1 backtracking
回溯遍历,每跳到一个位置i,就遍历i~i+nums[i]这些位置之中是否能过跳到终点,如果有一个能达到终点,就返回true
但这个方法超时了
private boolean canJump(int[] nums, int start, int max) {
if (nums[start] == 0 && start != nums.length-1)
return false;
if (start + max >= nums.length-1)
return true;
for (int i = max; i >= 1; i--) {
if (canJump(nums,start+i,nums[start+i]))
return true;
}
return false;
}
method 2
自顶向下动态规划,从method 1中我们可以看出,有些位置会重复遍历,因此我们引入记忆化搜索,还会回溯,但每到一个位置i时,先查看该位置是否是能够到达终点的位置(GOOD), 还是不能到达终点的位置(BAD),如果是不知道的位置(UNKNOWN),则遍历这个位置
通过使用dp降低了复杂度,存储了index i是否能到达终点的结果,当再经过这些index的时候不再需要计算
enum Index {
GOOD, BAD, UNKNOWN
}
Index[] index;
private boolean canJump2(int[] nums, int start) {
start = Math.min(start,nums.length-1);
if (index[start] != Index.UNKNOWN)
return (index[start] == Index.GOOD)?true:false;
int max = nums[start];
for (int i = max; i >= 1; i--) {
if (canJump2(nums,start+i)){
index[start] = Index.GOOD ;
return true;
}
}
index[start] = Index.BAD;
return false;
}
method 3
自底向上,从右边开始跳,递归转循环.先将每一个Index置为UNKNOWN,再把最后一个INDEX置为GOOD
public boolean canJump3(int[] nums) {
Index[] memo = new Index[nums.length];
for (int i = 0; i < memo.length; i++) {
memo[i] = Index.UNKNOWN;
}
memo[memo.length - 1] = Index.GOOD;
for (int i = nums.length - 2; i >= 0; i--) {
int furthestJump = Math.min(i + nums[i], nums.length - 1);
for (int j = i + 1; j <= furthestJump; j++) {
if (memo[j] == Index.GOOD) {
memo[i] = Index.GOOD;
break;
}
}
}
return memo[0] == Index.GOOD;
}
method 4 Greedy
从method 3 中再次得到启发,如果在位置i,且i~nums[i]+i这之中有一个GOOD INDEX,那么代表位置i也是个GOOD INDEX
遍历完如果lastPos = 0 则表示起点也是good Index,那么从起点也可以跳到终点
public boolean canJump4(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;
}
summary:
- (当方法超时的时候)发现是不是有些步骤被重复计算,如果有重复计算,那么就引入动态规划
- 反向思考,问的是从起点到终点,如果能从终点到起点,结果也是等价的
- 使用greedy 简化动态规划,进一步看清问题的本质