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

      方法一:DFS  小数据AC, 大数据挂掉

    class Solution {
    public:
         bool DFS(int A[],int n, int i)
        {
          if(i == n-1) return true;
          if(i >= n) return false;
          int num = A[i];
          if(num == 0) return false;
          for(int m = 1; m <= num ;m++)
          {
             bool f = DFS(A,n,i+m);
             if(f == true) return true; 
          }
          
          return false;
        }
        bool canJump(int A[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(n ==0) return true;
            return DFS(A,n,0) ;
        }
    };
    View Code

    方法二: 还是大数据未过

    class Solution {
    public:
        
        bool canJump(int A[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
           vector<bool> flag(n, false);
           flag[0] = true;
           for(int i = 0; i< n-1 ; i++)
           {
              if(flag[i] == false) continue;
              int m = A[i];
              for(int j =1; j<= m && j+i< n ; j++)
                  flag[i+j] = true;
           }
           
          return flag[n-1] ;
        }
    };
    View Code

     上一份代码超时的主要原因是内循环,所以要设法改进内循环。改进的方法是不再设定每一个可能的位置为true,而是维护一个可以抵达的最远的距离maxJump。如果当前的i<=maxJump,则可以更新maxJump =

    maxJump > i+A[i] ? maxJump : i+A[i]; 最后以maxJump > n-1来判断最后一个位置是否可达。 AC代码如下:

    class Solution {
    public:
        bool canJump(int A[], int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
           int maxJump = 0;
           for(int i = 0; i< n-1 ; i++)
           {
              if(i <= maxJump)
                 maxJump = maxJump > A[i]+i ? maxJump : A[i]+i  ;
                 
                if(maxJump >= n-1) return true;
           }
            
          return maxJump >= n-1 ;
        }
    };
  • 相关阅读:
    2.2.3 线程中断
    java枚举 用于声明持久化常量 和volley 请求头
    java获取昨天的日期
    使用LocalBroadcastManager
    大端模式与小端模式
    Android更新主线程UI的两种方式handler与runOnUiThread()
    android dialog圆角显示及解决出现的黑色棱角.(友情提示)
    html5中的新标签
    html中的title和alt
    Android开发之蓝牙Socket
  • 原文地址:https://www.cnblogs.com/graph/p/3209862.html
Copyright © 2011-2022 走看看