1. 程式人生 > >[LeetCode]45. Jump Game II &&貪心演算法

[LeetCode]45. 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.)

Note:
You can assume that you can always reach the last index.

Subscribe to see which companies asked this question

貪心演算法:

reach:變數維護能到達最遠處,當遍歷到i的時候,區域性最優解為A[i]+i,因此,此時的全域性最優解即為reach和A[i]+i的最大值:reach = max(reach, A[i] + i)  

last:上一步能到達的最遠位置

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int jump(vector<int>& nums) {
    int last=0,step=0,reach=0,len=nums.size();
    for(int i=0;i<len;i++)
    {
    	if(i>last)
    	{
    		last=reach;
    		step++;
    	}
    	reach=max(reach,nums[i]+i);
    }
    return step;
}
int main()
{
	int a[5]={2,3,1,1,4};
	vector<int> v(a,a+5);
	cout<<jump(v)<<endl;
}