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.)

就是给定一个数组,从头开始,每次最多可以跳跃步数为当前的数字,问最少跳多少次可以到结尾。例如给出的例子是2次,2先跳到3,然后3跳3步就到结尾了。要是2先跳2步到1,1只能跳1步到第二个1,又只能跳1步到4,总共3次。所以最少跳数应该是刚才的2.

我一开始想到了用动态规划。然后,很开心的写了。发现会TLE。动态的代码如下:

class Solution {
public:
    int jump(int A[], int n) {
        if (n == 1)
            return 0;
        vector<int> dp(n, INT_MAX);
        dp[n - 1] = 1;
        for (int i = n - 2; i > -1; --i)
        {
            if (A[i] + i >= n - 1)
                {dp[i] = 1;continue;}
            int min = INT_MAX;
            for (int j = i + 1; j < n && j <= i + A[i]; ++j)
            {
                if (dp[j] < min)
                    min = dp[j];
            }
            dp[i] = min + 1;
        }
        return dp[0];
    }
};
View Code

动态好理解。但是超时了。看了众多大神,这个不错。应该要用贪心:

class Solution {
public:
    int jump(int A[], int n) {
        if (n < 2) return 0;
        int canReach = 0; // 能到达的最远处
        int curReach = 0; // 当前所到达的最远处,如果i大于它了,才要跳到能达到的最远处(贪心)
        int jump = 0;
        for (int i = 0; i <= canReach && i < n; ++i)
        {
            if (i > curReach) // 要先判断i是否超过了当前能到达的地方,之后再更新能到达的最远
            {
                ++jump;
                curReach = canReach;
            }
            canReach = max(canReach, i + A[i]); //要在if判断后才更新能到达的最远
        }
        return jump;
    }
};

 

这是讨论组里的解法。很好啊。O(n)。

转载于:https://www.cnblogs.com/higerzhang/p/4060998.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值