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 };
  • 相关阅读:
    angularJs项目实战!02:前端的页面分解与组装
    angularJs项目实战!01:模块划分和目录组织
    django admin 导出数据简单示例
    django 学习之model操作(想细化)
    6.11大杂烩。。
    InlineModelAdmin对象的学习
    django-salmonella的使用
    python 保留两位小数
    Django 时间与时区设置问题
    Django学习
  • 原文地址:https://www.cnblogs.com/easonliu/p/3643675.html
Copyright © 2011-2022 走看看