leetcode Jump Game II
2014-06-18 22:15
465 查看
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 =
The minimum number of jumps to reach the last index is
(Jump
to the last index.
class Solution {
public:
/*贪心算法即可解决这个问题*/
int jump(int A[], int n) {
if(n<=0) return 0;
vector<int> step(n,0);
int maxIndex=0,max=A[0],last=0;
for(int i=1;i<n;i++){
if(last+A[last]>=i){ //如果在last可达的范围内,那么就可以直接由last跳转到这个地方
step[i]=step[last]+1;
}
else{ /*如果没有在last可达的范围内,那么i应该在max的范围内,选择由maxIndex坐标跳过来,在这里需要证明的两点1、maxIndex<i,因为for循环 2、step[maxIndex]已经在for循环之前已经计算出来,所以step[i]直接在step[maxIndex]的基础上+1即可*/
step[i]=step[maxIndex]+1;
last=maxIndex;
}
if(i+A[i]>max){
max=i+A[i];
maxIndex=i;
}
}
return step[n-1];
}
};
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
1step from index 0 to 1, then
3steps
to the last index.
class Solution {
public:
/*贪心算法即可解决这个问题*/
int jump(int A[], int n) {
if(n<=0) return 0;
vector<int> step(n,0);
int maxIndex=0,max=A[0],last=0;
for(int i=1;i<n;i++){
if(last+A[last]>=i){ //如果在last可达的范围内,那么就可以直接由last跳转到这个地方
step[i]=step[last]+1;
}
else{ /*如果没有在last可达的范围内,那么i应该在max的范围内,选择由maxIndex坐标跳过来,在这里需要证明的两点1、maxIndex<i,因为for循环 2、step[maxIndex]已经在for循环之前已经计算出来,所以step[i]直接在step[maxIndex]的基础上+1即可*/
step[i]=step[maxIndex]+1;
last=maxIndex;
}
if(i+A[i]>max){
max=i+A[i];
maxIndex=i;
}
}
return step[n-1];
}
};
相关文章推荐
- 【Leetcode】Jump Game II (DP)
- Leetcode_jump-game-ii(c++ and python version)
- [leetcode] Jump Game I and II
- Leetcode Jump Game II 解题报告
- LeetCode 045 Jump Game II
- LeetCode-Jump Game II
- 【LeetCode】Jump Game II 跳跃游戏II - 贪心 Medium
- LeetCode-Jump Game & Jump Game II
- LeetCode之Jump Game II
- LeetCode | Jump Game II
- LeetCode_Jump Game II
- #leetcode#Jump Game II
- LeetCode 45/55. Jump Game i, ii
- LeetCode-45-Jump Game II DP
- 57 leetcode - Jump Game II
- Leetcode Jump Game II
- leetcode-Jump game II
- LeetCode_45---Jump Game II
- leetcode - Jump Game II
- [LeetCode P45] Jump Game II