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来实现,但这种方法是超时的。代码如下:
1 class Solution { 2 public: 3 bool canJump(int A[], int n) { 4 if(n == 0) return false; 5 return dfs(A,n,0); 6 } 7 bool dfs(int A[], int n, int start){ 8 if(start >= n-1) return true; 9 for(int i = 1; i <= A[start]; i++){ 10 if(dfs(A,n,start+i)) return true; 11 } 12 return false; 13 } 14 };
之后看了leetcode-cpp.pdf中的解法,发现可以用贪心算法来解。该题有这样一个性质,如果最后一个元素可以达到,那么所有元素都可以达到,根据这个性质我们可以用贪心算法。代码如下:
1 class Solution { 2 public: 3 bool canJump(int A[], int n) { 4 int reach = 1; 5 for(int i = 0; i < reach && reach < n; i++){ 6 reach = max(reach, i+1+A[i]); 7 } 8 return reach >= n; 9 } 10 };