45. Jump Game II
来源:互联网 发布:淘宝冻结卖家资金多久 编辑:程序博客网 时间:2024/05/17 02:59
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.)
Note:
You can assume that you can always reach the last index.
思路是利用贪心算法,当到达每一个点的步数都最小时,到达最后一个点的jump数自然最小。这里利用reach变量记录当前每个点能跳到的最远距离,利用count数组记录到达每一点的最小步数。有一点要明白,即当我们的reach第一次到达终点时,此时的count一定已经是最小的了,其后的点的jump数一定会大于等于该点的jump。
int jump(vector<int>& nums) {
int i = 0;
int n = nums.size();
int count[n];
for(int i = 0; i < n; i++){
count[i] = 1000000;
}
count[0] = 0;
for (int reach = 0; i < n && i <= reach; ++i){
reach = max(i + nums[i], reach);
if(reach <= n - 1){
count[reach] = min(count[i] + 1, count[reach]);
}
else
count[n - 1] = min(count[i] + 1, count[n - 1]);
}
return count[n - 1];
}
int i = 0;
int n = nums.size();
int count[n];
for(int i = 0; i < n; i++){
count[i] = 1000000;
}
count[0] = 0;
for (int reach = 0; i < n && i <= reach; ++i){
reach = max(i + nums[i], reach);
if(reach <= n - 1){
count[reach] = min(count[i] + 1, count[reach]);
}
else
count[n - 1] = min(count[i] + 1, count[n - 1]);
}
return count[n - 1];
}
0 0
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- Re###port
- HDU 1799
- 提高css代码技巧
- 一些哲思
- HDU 2084 数塔 dp
- 45. Jump Game II
- C++中的矩阵实验室Egien
- 邮票分你一半(dfs)
- View的滑动方法
- Luogu P1709 [USACO5.5]隐藏口令Hidden Password
- 石家庄明天打折22309
- 辛集明天打折69449
- Android自定义控件
- iOS-插入广告-InMobi使用教程