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为上一步,nums[i]为当前步,故取max(step-1, nums[i])则为局部最优,且循环至结束则为全局最优。
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
if(len == 0 || len == 1){
return true;
}
int step = nums[0];
for(int i = 1; i < len; i++){
if(!step){
return false;
}
step--;
if(nums[i] > step){
step = nums[i];
}
if(step + i >= len - 1){
return true;
}
}
}
};