参考链接
http://blog.youkuaiyun.com/pickless/article/details/9855891
http://www.cnblogs.com/tgkx1054/archive/2013/05/23/3095115.html
http://www.cnblogs.com/xinsheng/p/3510504.html
题目描述
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.
Jump Game II
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.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
题目分析
class Solution {
public:
bool canJump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int max = 0;
for (int i = 0; i < n && i <= max; i++) {
max = A[i] + i > max ? A[i] + i : max;
}
return max >= n - 1;
}
};Jump Game II
class Solution {
public:
int jump(int A[], int n)
{
int *step=new int[n];
memset(step,0,sizeof(step));
int lasti=0,maxreach=A[0],reachindex;
for(int i=1;i<n;i++)
{
if(lasti+A[lasti]>=i)
{
step[i]=step[lasti]+1;
}
else
{
step[i]=step[reachindex]+1;
lasti=reachindex;
}
if(i+A[i]>maxreach)
{
maxreach=i+A[i];
reachindex=i;
}
}
return step[n-1];
}
};
class Solution {
public:
int jump(int A[], int n) {
if(n <= 1)
return 0;
int start = 0, end = 0;
int cnt = 0;
while(end < n-1) {
int maxdis = 0;
for(int i = start; i <= end; i ++) {
maxdis = max(maxdis, A[i]+i);
}
start = end+1;
end = maxdis;
cnt ++;
}
return cnt;
}
};

这篇博客介绍了LeetCode上的两道题目——Jump Game和Jump Game II,涉及非负整数数组中跳跃到达最后一个元素的可能性和最小跳跃次数。提供了题目描述和分析,并推荐了C++的学习资源。

593

被折叠的 条评论
为什么被折叠?



