45. Jump Game II
Given an array of non-negative integers, you are initiallypositioned at the first index of the array.
Each element in the array represents your maximum jump length atthat position.
Your goal is to reach the last index in the minimum number ofjumps.
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.)
开始时想的DFS----复杂度为o(n^c)之类的把(c>2),超时了
不过还是说下思路:
DFS都可以归结为递归或者堆栈处理----不过递归好理解些。
既然是递归必然有An=f(An-1)
和A0=c
于是递归部分代码如下:
public int subJump(int[] nums,int index,int sum){
if(index>=nums.length) return sum;
int min=Integer.MAX_VALUE;
for(int j=1,tmp;j<=nums[index];j++){
tmp=subJump(nums,index+j,sum+1);
min=tmp<min?tmp:min;
}
return min;
}
代码:
public class Solution {
public int jump(int[] nums) {
if(nums==null||nums.length==0) return 0;
int res=0;
res=subJump(nums,0,0);
return res;
}
//2,3,1,1,4
public int subJump(int[] nums,int index,int sum){
if(index>=nums.length) return sum;
int min=Integer.MAX_VALUE;
for(int j=1,tmp;j<=nums[index];j++){
tmp=subJump(nums,index+j,sum+1);
min=tmp<min?tmp:min;
}
return min;
}
}
DFS走了许多无用路径,优化之后就是BFS---遍历所有元素即可
设置三个量
Level,currentMax,nextMax
首先将A[0]归为第一级集合(即level=0),然后将A[0]能跳到的所有位置放入第二级集合(leve=1),再遍历第二级集合找到第二级集合能跳到的第三级集合。然后循环下去直到能够跳到最后一个元素。
代码:
public class Solution {
public int jump(int[] nums) {
while(nums.length<2) return 0;
int level=0;currentMax=0,i=0,nextMax=0;
while(i<=currentMax){
level++;
for(;i<=currentMax;i++){
nextMax=Math.max(nextMax,nums[i]+i);
if(nextMax>=nums.length-1) return level;
}
if(currentMax==nextMax) return Integer.MAX_VALUE
currentMax=nextMax;
}
}
}