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.
Example:
Input: [2,3,1,1,4]
Output: 2
Explanation: 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.
找出达到最后一个的最小步数
2 3 1 1 4
那么就是找到能达到4的最短路径
能到到4的最小的 前一个节点为3
故为 找到3所在的最短路径
实现方法如下:
//找出从第一个到最后一个的最短步骤
public int jump(int[] nums) {
int size = nums.length-1;
int res[] = new int[size+1];
res[0] = 0;
for(int i=1;i<=size;i++) {
res[i]=Integer.MAX_VALUE;
}
jump(nums,size,size,res);
return res[size];
}
public int jump(int[] nums,int target,int endIndex,int res[]) {
if(target == 0) {
return res[target];
}
for(int i=0;i<endIndex;i++) {
if(i+nums[i]>=target) {
res[target] = Math.min(jump(nums,i,i,res)+1,res[target]);
break;
}
}
return res[target];
}
可以对以上方法进行优化 ,具体优化方案 如下:
public int jumpBetter(int[] nums) {
if(nums==null||nums.length<2)
return 0;
int target = nums.length-1;
int res=0;
while(target!=0) {
for(int i=0;i<target;i++) {
if (i + nums[i] >= target) {
res++;
target = i;
}
}
}
return res;
}