首页 > 其他 > 详细

Jump Game II

时间:2014-04-12 18:17:26      阅读:514      评论: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.)

思路:这道题与Jump Game的解法思路差不多,只不过是要记录跳了几次。每次记录能跳的最大值,然后循环遍历,直到到达n-1索引。最后就是输出跳了多少跳,即最小的跳数。本题时间复杂度O(n2)。

bubuko.com,布布扣
class Solution {
public:
    int jump(int A[], int n) {
        if(n<=1)
            return 0;
        int begin=0;
        int end=0;
        int step=0;
        for(;end<n-1;)
        {
            int newEnd=begin;
            for(int i=begin;i<=end;i++)
                newEnd=max(newEnd,i+A[i]);
            if(newEnd==end)
                return -1;
            begin=end+1;
            end=newEnd;
            step++;
        }
        return step;
    }
};
bubuko.com,布布扣

 解法二:可以使用动态规划的思路来解题。

bubuko.com,布布扣
class Solution {
public:
    void min_step(int A[],int n,vector<int> &step)
    {
       for(int i=1;i<n;i++)
       {
           for(int j=0;j<i;j++)
           {
               if(j+A[j]>=i)
               {
                   int minstep=step[j]+1;
                   if(minstep<step[i])
                   {
                       step[i]=minstep;
                       break;
                   }
               }
           }
       }
    }
    int jump(int A[], int n) {
        if(n==0)
            return INT_MAX;
        vector<int> step(n);
        step[0]=0;
        for(int i=1;i<n;i++)
        {
            step[i]=INT_MAX;
        }
        min_step(A,n,step);
        return step[n-1];
    }
};
bubuko.com,布布扣

 

Jump Game II,布布扣,bubuko.com

Jump Game II

原文:http://www.cnblogs.com/awy-blog/p/3658166.html

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