原题:
解决方法:
代码:
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.
解决方法:
用bfs比较容易得出结果,其实也符合贪婪的思想。
每次跳跃中,都找到下一步能跳得最远的那一步。
代码:
int jump(vector<int>& nums) {
int n = nums.size();
if (n <= 1)
return 0;
int step = 0, curMax = 0, pos = 0;
while(curMax - pos + 1 > 0){
++step;
int nextMax = 0;
for(; pos <=curMax; pos++){
nextMax = max(nextMax, nums[pos] + pos);
if (nextMax >= n-1)
return step;
}
curMax = nextMax;
}
return 0;
}