题目
- 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.
解题思路
贪心法,每次走一步,递推公式如下:
if steps[i] < steps[i+1]
then jump(steps[i+1])
最后
if(steps[i] < 0)
then return false
解题代码
class Solution {
public:
bool canJump(const vector<int>& nums) {
vector<int>::size_type n = nums.size();
int v = nums[0];
for (vector<int>::size_type i = 1; i < n; i++) {
if (--v < 0) return false;
if (v < nums[i]) v = nums[i];
}
return (v >= 0) ? true : false;
}
};