首页 > 其他 > 详细

45. Jump Game II (Array, DP)

时间:2015-10-14 23:23:20      阅读:247      评论:0      收藏:0      [点我收藏+]

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

思路:此处不能用贪心算法,因为局部的算少跳数,并不适用于全局。

class Solution {
public:
    int jump(int A[], int n) {
        int maxPos = 0; //已经处理过最少步数的最远位置
        int f[n]; //表示到i所需的最少步数
        f[0] = 0;
        
        for(int i = 0; i <= maxPos; i++)
        {
            int pos = i + A[i]; //i能够到达的最远位置
            if (pos >= n)
                pos = n - 1;
                
            if (pos > maxPos)
            {
                for(int j = maxPos + 1; j <= pos; j++)
                    f[j] = f[i] + 1; //状态转移方程:注意i之后即使有其他位置x能到达j位置,步数必定>=这个值,因为f[i]<=f[x] if i<=x
                maxPos = pos; 
            }
            
            if (maxPos == n - 1)
                return f[n-1];
        }
    }
};

 

45. Jump Game II (Array, DP)

原文:http://www.cnblogs.com/qionglouyuyu/p/4878928.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!