题目描述:
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
.
使用贪心法,假设当前位于元素i,如果nums[i]<=0,那么不可能到达最后一个元素,否则下一跳选择的步数j需要满足:max(j+nums[i+j]) 其中j>=1 且j<=nums[i]
AC代码如下:
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
if (n == 0 || nums[0] >= n - 1) return true;
for (int i = 0; i < n;){
if (nums[i] <= 0) return false;
int max_step = 0;
int select_step = 0;
if (i + nums[i] >= n - 1) return true;
for (int j = 1; j <= nums[i];++j){
if (j + nums[i + j] > max_step){
max_step = j + nums[i + j];
select_step = j;
}
}
i += select_step;
}
return true;
}
};