问题描述:
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.)
题目的意思:与第55题不同的地方是,这次需要让你找出从起始位置跳最少得步骤能够到达最后一个元素的位置。
题目的意思清楚了,这次依旧是使用贪心的算法。我们以下图为例:数组A的元素是3,4,3,1,0,7.对于每个位置i,最少能往前跳一步,最多能往前跳A[i]步长。我们定义i可达区间即f(i) = [i+1,i+A[i]],图中A[0]元素的可达区间就是[1,3]。局部的最优解定义是i往后跳了j步到达可达区间f(i), 该可达区间内元素能够跳到的最远距离对应的可达区间内元素下标就是局部最优解。比如对于在起始位置0,可达区间是[1,3],[1,3]内元素能够跳到最远的距离是位置5,所以下一跳地址应该是位置1或者2(1跟2都是到达最远位置5,我的代码里是选择2)
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() == 0 || nums.size() == 1)return 0;
int index = 0;
int count_step = 0;
while(index < nums.size()){
count_step++;
int next_index = index;
int max_step = 0;
for(int i = nums[index]; i >= 1; --i){
if(i + index > nums.size() - 1)continue;
else if(index + i == nums.size() - 1)return count_step;
else if(index + i + nums[index + i] == nums.size() - 1)return count_step + 1;
if(max_step < i + nums[index + i]){
next_index = index + i;
max_step = i + nums[index + i];
}
}
index = next_index;
}
return -1;
}
};