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

[leetcode]Jump Game II

时间:2014-11-24 20:51:50      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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


基本思路:

用一个数组保存到index的最小的步数。 如果新的走法可以使得到index的最小步数变小,就更新之。最后返回对last index的最小步数。同时可以设置变量记录到目前为止可以到达的最远的index,用于剪枝。具体请看代码:


代码:

   int jump(int A[], int n) {  //C++
        if(n == 1)
            return 0;
            
        int head = 0;
        vector<int> record(n,n);
        record[0] = 0;
        for(int i = 0; i < n; i++)
        {
            if(A[i] + i > head)
            {
                head = A[i] +i;
                for(int j = 1; j < n-i&&j <= A[i]; j++)
                    if(record[i+j] > record[i]+1 )
                    {
                        record[i+j] = record[i]+1;
                        if(i+j == n-1)
                            return record[i]+1;
                    }
            }                    
        }
        return record[n-1];
        
    }


[leetcode]Jump Game II

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/41451271

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