您的位置:首页 > 其它

leetcode-jump game

2015-05-21 10:58 405 查看
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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: