• leetcode -- Jump Game


    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.

    Determine if you are able to reach the last index.

    For example:
    A = [2,3,1,1,4], return true.

    A = [3,2,1,0,4], return false.

    [解题思路]

    1.一维DP,jump[i]表示到达位置i剩余的最大步数

     1 public boolean canJump(int[] A) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int len = A.length;
     5         //using DP
     6         int[] jump = new int[len];
     7         jump[0] = 0;
     8         
     9         for(int i = 1; i < len; i++){
    10             jump[i] = Math.max(jump[i - 1], A[i - 1]) - 1;
    11             if(jump[i] < 0){
    12                 return false;
    13             }
    14         }
    15         return true;
    16     }

     2.二维DP

    f(i)表示是否可以从position 0到达i

    f(i) = OR 'f(j) && A[j] + j >= i' j = 0,...,i - 1

    时间复杂为O(N^2), 大数据集会超时

     1 public boolean canJump(int[] A) {
     2         if(A.length == 0){
     3             return true;
     4         }
     5         int len = A.length;
     6         boolean[] f = new boolean[len];
     7         f[0] = true;
     8         for(int i = 1; i < len; i++){
     9             for(int j = 0; j < i; j++){
    10                 f[i] = f[i] || (f[j] && (A[j] + j >= i));
    11             }
    12         }
    13         return f[len - 1];
    14     }

     3.Greedy

    维护一个maxDis变量,表示当前可以到达的最大距离

    当maxDis >= len - 1表示可以到达

    每经过一点都将maxDis 与 i + A[i]进行比较,更新最大值

     1 public boolean canJump(int[] A) {
     2         if(A.length == 0){
     3             return true;
     4         }
     5         int len = A.length;
     6         int maxDis = 0;
     7         for(int i = 0; i < len; i++){
     8             
     9             if(maxDis < i){
    10                 return false;
    11             }
    12             maxDis = Math.max(maxDis, i + A[i]);
    13             if(maxDis >= len - 1){
    14                 return true;
    15             }
    16         }
    17         
    18         return false;
    19     }
  • 相关阅读:
    [USACO15JAN]草鉴定Grass Cownoisseur (分层图,最长路,$Tarjan$)
    P1558 色板游戏 (线段树)
    [Vani有约会]雨天的尾巴 (线段树合并)
    UVA11806 Cheerleaders (容斥)
    [JSOI2007]建筑抢修 (贪心)
    [POI2015]KIN (线段树)
    [六省联考2017]组合数问题 (矩阵优化$dp$)
    [BZOJ2957] 楼房重建 (线段树,递归)
    [USACO Section 5.3]量取牛奶 Milk Measuring (动态规划,背包$dp$)
    P2647 最大收益 (动态规划)
  • 原文地址:https://www.cnblogs.com/feiling/p/3241934.html
Copyright © 2020-2023  润新知