首页 > 代码库 > [LeetCode] Jump Game

[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.

这个题要小心各种陷阱,一不小心就会死循环什么的。

class Solution {public:    bool canJump(int A[], int n) {        if(n<=1)          return true;//输入[0]输出true        int Index = A[0];        while(Index<n-1){           if(A[Index]!=0)             Index += A[Index];           else{               int Index0 = Index;               for(int i = Index0-1;i>=0;i--){//遇到不前进的,往前回退一步,因为能到i,经过前面的步骤也能到i-1;                   Index = i + A[i];                   if(Index>Index0)                       break;                   else                       continue;                              }//end for                              if(Index<=Index0)//经过处理后依然跨不过坎                   return false;           }//end if              }//end while        if(Index>=n-1)            return true;        else            return false;    }};