[LeetCode]045-Jump Game II

来源:互联网 发布:家长监控软件 编辑:程序博客网 时间:2024/05/21 10:30

题目:
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.)

Solution:
思路:用DFS或BFS都可以做,但肯定超时了。
贪心算法的思想可以用在这。这段代码也是参考了其他博客而来的,理解起来有不少困难,结合例子来看会稍微容易点。

 int jump(vector<int>& nums)     {        int n = nums.size();        int i;        int maxstep = 0;        int waitstep = 0;        int step = 0;        for(i = 0;i<n;i++)        {            if(waitstep < i) //设置waitstep,是保证它所跳的步数在范围内。超过了就需要跳了            {                step++;                waitstep = maxstep; //更新最大范围步数            }            maxstep = max(maxstep,nums[i] + i);//最大范围        }        return step;    }
0 0