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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
Note:
You can assume that you can always reach the last index.
刚开始想用DP,但是要循环判断前面的每一项,复杂度O(n^2),
package l45;
/*
* 分别对到达该处需要的最小step进行求解
*/
public class CopyOfSolution {
public int jump(int[] nums) {
int len = nums.length, cur_min = Integer.MAX_VALUE;
int[] minReach = new int[len];
for(int i=0; i<len; i++)
minReach[i] = Integer.MAX_VALUE;
minReach[0] = 0;
for(int i=1; i<len; i++) {
//if(cur_min >= minReach[i]) break;
for(int j=0; j<i; j++) {
if(nums[j] + j >= i) {
if(minReach[j]!=Integer.MAX_VALUE && minReach[j]+1<minReach[i]) {
minReach[i] = minReach[j]+1;
}
}
}
}
return minReach[len-1];
}
}
考虑到这种解法是:分别对到达该处需要的最小step进行求解,每次都可能会达到末尾,但是不一定是最短的,所以换种perspective考虑,考虑步数一步步增加,并求出最远能到多少,当可以到达末尾,跳出循环即可
*
* 步数一点一点累加,最远能达到最后即可跳出循环
*/
public class Solution {
public int jump(int[] nums) {
int step = 0;
int curMax = 0, preMax = 0, nextMax = 0;
if(nums.length == 1) return 0;
while(true) {
step ++;
for(int i=preMax; i<=curMax; i++) {
if(i+nums[i]>nextMax) nextMax = i+nums[i];
}
if(nextMax >= nums.length-1) return step;
preMax = curMax;
curMax = nextMax;
}
}
}
每个位置只需要遍历一次,所以BFS可以剪枝很多
class Solution(object):
def jump(self, a):
"""
:type nums: List[int]
:rtype: int
"""
if len(a)<=1: return 0
step = 0
cur_min, cur_max = 0, 0
while cur_max<len(a)-1:
next_max = cur_max+1
for i in range(cur_min, cur_max+1):
next_max = max(i+a[i], next_max)
cur_min, cur_max = cur_max+1, next_max
step+=1
return step
s=Solution()
print(s.jump([2,3,1,1,4]))