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
.
分析:DP
从第一个点开始走,每次求得当前可达点(i < max)可到达的最大值。
遍历完数组后,若最大值大于等于n-1,则返回true,否则返回false;
class Solution {
public:
int max(int a,int b)
{
if(a > b)
return a;
else
return b;
}
bool canJump(vector<int>& nums) {
int n = nums.size();
if(n == 0)
return true;
int max_reach = nums[0];
int i = 0;
for(i = 1;i<n;i++)
{
if(i > max_reach)
return false;
else
max_reach = max(max_reach,nums[i]+i);
}
if(max_reach >= n-1)
return true;
else
return false;
}
};