zoukankan      html  css  js  c++  java
  • [Leetcode] 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.)

    动态规划,注意剪枝,要不然要超时!

     1 class Solution {
     2 public:
     3     int jump(int A[], int n) {
     4         int *a = new int[n];
     5         for (int i = 0; i < n; ++i) {
     6             a[i] = INT_MAX;
     7         }
     8         a[0] = 0;
     9         for (int i = 1; i < n; ++i) {
    10             for (int j = 0; j < i; ++j) {
    11                 if (j + A[j] >= i && a[i] > a[j] + 1) {
    12                     a[i] = a[j] + 1;
    13                     break;
    14                 }
    15             }
    16         }
    17         return a[n-1];
    18     }
    19 };

     果然HARD级别的题目有优于O(n^2)的算法,下面是O(n)的算法。

     res:目前为止的jump数

     curRch:从A[0]进行ret次jump之后达到的最大范围

     curMax:从0~i这i+1个A元素中能达到的最大范围

     当curRch < i,说明ret次jump已经不足以覆盖当前第i个元素,因此需要增加一次jump,使之达到记录的curMax。

     1 class Solution {
     2 public:
     3     int jump(int A[], int n) {
     4         int res = 0;
     5         int curRch = 0, curMax = 0;
     6         for (int i = 0; i < n; ++i) {
     7             if (curRch < i) {
     8                 ++res;
     9                 curRch = curMax;
    10             }
    11             curMax = max(curMax, i + A[i]);
    12         }
    13         return res;
    14     }
    15 };
  • 相关阅读:
    奋斗了一晚上,搞定了Ant
    我很成功,我很失败
    管理复杂性
    Rapid framework(SSH)数据流概述
    Strtus2 Convention Plugin学习(转)
    16X16 经典silk图标 (famfamfam.com)
    v512 Oracle数据库实用教程 演示用ppt(转pdf)
    RapidFramework使用Oracle的步骤
    oracle 找出最耗资源的sql (dolphin_ygj)
    jquery validate 中文化
  • 原文地址:https://www.cnblogs.com/easonliu/p/3643675.html
Copyright © 2011-2022 走看看