leetcode——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.

首先,定义一个数组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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值