zoukankan      html  css  js  c++  java
  • 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];
        }
    };
  • 相关阅读:
    关于s3c6410 实现opengl的分析
    ARM9和ARM11的区别
    ARM9E 和 cortex a8 NEON 优化效率的对比
    armv6 的特点
    AMBA总线新一代标准AXI分析和应用
    linux下如何模拟按键输入和模拟鼠标
    opengl es 学习
    Jlink初使用
    Allegro 制作金手指封装
    世界之窗浏览器设置google搜索[转]
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3658166.html
Copyright © 2011-2022 走看看