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 ;

    }

};

 

你可能感兴趣的:(LeetCode)