Jump Game <leetcode>

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.

算法:首先看能一次性到达最后一点的点,比如2,3,1,1,4,  能到达A[4]的是A[1],A[3],此时A[1]肯定也能到达A[1]后面所有的点,所以把A[1],当做关键点,向前知道到达第一个节点。也可以把A[3]当做关键点,因为当数据很多时,找右侧的第一个点比较容易,找左边第一个点比较费时。两个代码如下:

 1 //  52ms
 2 
 3 
 4 class Solution {
 5 public:
 6     bool canJump(int A[], int n) {
 7         if(n==1)  return true;
 8         else
 9         {
10             for(int i=0;i<=n-2;i++)
11             {
12                 if(A[i]+i>=n-1)
13                 {
14                     return canJump(A,i+1);
15                 }
16             }
17             return false;
18         }
19     }
20 };
 1 //44ms
 2 
 3 
 4 class Solution {
 5 public:
 6     bool canJump(int A[], int n) {
 7         if(n==1)  return true;
 8         else
 9         {
10             for(int i=n-2;i>=0;i--)
11             {
12                 if(A[i]+i>=n-1)
13                 {
14                     return canJump(A,i+1);
15                 }
16             }
17             return false;
18         }
19     }
20 };
原文地址:https://www.cnblogs.com/sqxw/p/3980061.html