题目链接: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. 

这道题的要求是给定一整数数组,数组元素表示每次可以跳跃的最大距离。然后初始位置在数组的第一个元素,返回能否数到达最后元素。

采用贪心的思路,采用reach变量维护能到达最远处,即为全局最优解。当遍历到i的时候,局部最优解为A[i]+i,因此,此时的全局最优解即为reach和A[i]+i的最大值:reach = max(reach, A[i] + i)。

还有Jump Game II这道题,是这题的提升,需要计算到达最后元素时的最小步数。

时间复杂度:O(n)

空间复杂度:O(1)

 1 class Solution
 2 {
 3 public:
 4     bool canJump(int A[], int n)
 5     {
 6         int reach = 0;
 7         for(int i = 0; i <= reach && i < n; ++ i)
 8             reach = max(reach, A[i] + i);
 9         
10         return reach >= n - 1;
11     }
12 };