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

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

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;
    }
};

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

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];
    }
};
原文地址:https://www.cnblogs.com/awy-blog/p/3658166.html