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
.
思路:
最开始用动规,结果超时。后来使用贪心,用step记录每一步可以最多向后移动的距离,AC。
代码:
1 int max(int a, int b){ 2 if(a > b) 3 return a; 4 return b; 5 } 6 bool canJump(int A[], int n) { 7 // Note: The Solution object is instantiated only once and is reused by each test case. 8 if(n == 0) 9 return false; 10 int step = A[0], i; 11 for(i = 1; i < n; i++){ 12 if(step > 0) 13 step = max(step-1, A[i]); 14 else 15 return false; 16 } 17 return true; 18 }