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
.
解题技巧:
采用贪心的方法。开始时,step = nums[0]; 到达下一个位置时,step-- ,并且令step = max(step, nums[i]),这样step能够一直保持最大移动步数。
代码:
bool canJump(vector<int>& nums)
{
int step;
if(nums.empty()) return false;
step = nums[0];
for(int i = 1 ; i < nums.size(); i ++)
{
if(step > 0)
{
step --;
step = max(step, nums[i]);
}
else return false;
}
return true;
}