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.)
与 jump game I 一样 都是用贪心策略,每一步局部最优 。来得到全局最优。
int jump(vector<int>& nums)
{
int len = nums.size();
if(len <= 1)
{
return 0;
}
int reach = 0;
int pos;
int j;
int M;
int sum = 0;
while(reach < len)
{
// if(nums[reach] == 0)
// {
// return 0;
// }
if(reach + nums[reach] >= len - 1)
{
//cout << "**" << endl;
return sum + 1;
}
j = 1;
pos = reach;
M = 0;
cout << "*" << endl;
while(j <= nums[reach])
{
if(nums[reach + j] + reach + j > M)
{
// if(nums[reach + j] + reach + j >= len - 1)
// {
// cout << "*" << endl;
// return sum + 1;
// }
M = nums[reach + j] + reach + j;
pos = reach + j;
}
++ j;
}
reach = pos;
++ sum;
//cout << pos << endl;
// if(nums[reach] == 0)
// {
// return 0;
// }
//++ sum;
}
return sum;
}