您的位置:首页 > 其它

leetcode Jump Game II

2014-06-18 22:15 399 查看
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:
/*贪心算法即可解决这个问题*/
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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: