题目:
Jump Game II
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.)
分析:
贪婪算法,每跳一步都要求“利益最大化”(即每一步都要跳到能延伸最远的那个下标)。
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size()<=1)
return nums.size()==1?0:-1;
if(nums[0]==0)
return -1;
int count=0,right=nums[0];//right是能跳到最右边的下标
for(int i=0;i<nums.size();)
{
++count;//肯定要跳一步
if(right>=nums.size()-1)//到达终点,结束
return count;
int tmp=0,index=-1;
for(int j=i+1;j<=right;++j)//找到能跳最远的那个下标
{
if(tmp<j+nums[j])
{
tmp=j+nums[j];
index=j;
}
}
if(tmp<=right)//无法超越上一步,则跳不到终点
return -1;
else
{
right=tmp;
i=index;//此行代码确定这一轮循环跳到哪个下标
}
}
return -1;
}
};