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 {
bool find_prior(vector<int> nums,vector<int> &jump,int pos)
{
if(nums[pos]+pos>=nums.size()-1)
{
jump[nums.size()-1] = jump[pos] + 1;
return true;
}
for(int i=1;i<=nums[pos];i++)
{
jump[pos+i] = min(jump[pos+i],jump[pos]+1);
}
return false;
}
public:
int jump(vector<int>& nums) {
vector<int> jump(nums.size(),nums.size());
jump[0] = 0;
for(int j=0;j<nums.size()-1;j++)
{
if(j>=1&&nums[j]<=nums[j-1]-1)
continue;
if(find_prior(nums,jump,j))
break;
}
return jump[nums.size()-1];
}
};
性能:
参考答案:
class Solution {
public:
int jump(vector<int>& nums)
{
int n = nums.size();
int reach = 0;
int last_reach = 0;
int step = 0;
for(int i=0; i <= reach && i < n; ++i)
{
if(i > last_reach)
{
++step;
last_reach = reach;
}
reach = max(nums[i] + i, reach);
}
if( reach < n-1)
return -1;
return step;
}
};