leetcode——Jump Game II

来源:互联网 发布:nba常规赛数据 编辑:程序博客网 时间:2024/06/02 04:10

题目:

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 is2. (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.

首先,定义一个数组min_step,min_step[i]表示跳到i需要的最少步数,迭代并更新min_step,最后返回min_step.back()即可。

超时但是比较好理解的方法(动态规划):

class Solution {public:    int jump(vector<int>& nums) {        if (nums.size() <= 1)        {            return 0;        }        vector<int> min_step(nums.size(), 0);//min_step[i]表示从起点跳到i需要的最小的跳跃次数        for (int i = 1; i < nums.size(); ++i)        {            int min_value = INT_MAX;            for (int j = 0; j < i; ++j)//寻找位置j其可以一步跳到i且min_step[j]最小,用它更新的min_step[i]也最小            {                if (j + nums[j] >= i)                {                    min_value = min(min_step[j], min_value);                }            }            min_step[i] = min_value + 1;        }        return min_step.back();    }};
尽管上面的这个方案很好理解,但是会超时。

解决这个问题的更好的方法是贪心算法,对于每一个起跳点每次都尝试跳到最远的地方farthest,最先碰到终点的方案就是步数最小的方案。

class Solution {public:    //如果存在位置a和b,且a和b都可以一步跳到终点,如果a < b那么从a跳到终点的步数肯定不大于从b跳到终点的步数    int jump(vector<int>& nums) {        if (nums.size() <= 1)        {            return 0;        }        vector<int> min_step(nums.size(), 0);//min_step[i]表示从起点跳到i需要的最小的跳跃次数        int farthest = 0;//始终指向目前能够达到的最远距离        for (int i = 0; i < nums.size(); ++i)        {            int farthest_curr = max(nums[i] + i, farthest);//当前轮能够达到的最远位置            if (farthest_curr >= nums.size() - 1) //可以触及终点            {                return min_step[i] + 1;            }            //j从上一轮能够触及的最远的地方的后一个位置开始更新            for (int j = farthest + 1; j <= farthest_curr && j < nums.size(); ++j)            {                min_step[j] = min_step[i] + 1;            }            //从i起跳可以触及的最远位置为i + nums[i]            farthest = farthest_curr;        }        return -1;    }};



0 0
原创粉丝点击