码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Jump Game II

时间:2014-10-30 01:37:50      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   for   sp   

题目:

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。动态的代码如下:

bubuko.com,布布扣
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) {
        int ret = 0;
        int last = 0;
        int curr = 0;
        for (int i = 0; i < n; ++i) {
            if (i > last) {
                last = curr;
                ++ret;
            }
            curr = max(curr, i+A[i]);
        }
        return ret;
    }
};

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

leetcode Jump Game II

标签:style   blog   http   io   color   os   ar   for   sp   

原文地址:http://www.cnblogs.com/higerzhang/p/4060998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!