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.
使用广度遍历,每走一步,遍历可以走的所有路径
[]
[1,2,3,4,5]
[1,1,1,1,1,1,1,1]
[1]
package leetcodeArray;
public class Leetcode45JumpGameII {
public int jump(int[] nums) {
int i = 0, j = 1, steps = 0, n = nums.length;
while(j < n){
int endj = Math.min(nums[i] + i + 1, n);
while(j < endj){
if(nums[j] + j > nums[i] + i ) i = j;
j++;
}
System.out.println(endj);
steps++;
}
return steps;
}
}
int jump(int A[], int n) {
if(n<2)return 0;
int level=0,currentMax=0,i=0,nextMax=0;
while(currentMax-i+1>0){ //nodes count of current level>0
level++;
for(;i<=currentMax;i++){ //traverse current level , and update the max reach of next level
nextMax=max(nextMax,A[i]+i);
if(nextMax>=n-1)return level; // if last element is in level+1, then the min jump=level
}
currentMax=nextMax;
}
return 0;
}
class Solution {
public:
int jump(int A[], int n) {
vector<int> track(n, 0);
for(int i=1; iint min = INT_MAX;
for(int j=0; jif(track[j] < min && A[j]+j >= i)
min = track[j];
}
track[i] = min+1;
}
return track[n-1];
}
};