12.2—贪心法—Jump Game II
来源:互联网 发布:社交网络剧情 编辑:程序博客网 时间:2024/06/05 23:52
描述
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]
e 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.)
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]
e 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.)
#include<iostream>#include<vector>using namespace std;bool JumpGameII(int a[], int n, int &minstep, vector<int> &path){if (a == NULL || n <= 0||(a[0]==0&&n==1))return false;int reachindex = 0;int nextindex = 0;path.push_back(0);for (int i = 0; i < n-1;){if (a[i] == 0 && reachindex == i)return false;if (a[i] == 0 && reachindex > i)i++;for (int j = i + 1; j <= a[i] + i; j++){if (a[j] + j>=reachindex){reachindex = a[j] + j;nextindex = j;}}path.push_back(nextindex);i = nextindex;minstep++;if (reachindex >= n - 1){path.push_back(n - 1);minstep++;return true;}}}int main(){const int n=5;int a[n] = { 3,4,1,1,4};int minstep = 0;vector<int> path;bool flag = JumpGameII(a, n, minstep,path);if (flag){cout << "need minimum number of jumps is:" << minstep << endl;cout << "solution:";for (int i = 0; i < path.size(); i++)cout << path[i] << " ";}}
阅读全文
0 0
- 12.2—贪心法—Jump Game II
- 贪心 Jump Game II
- 12.1—贪心法—Jump Game
- 贪心法、动态规划——jump-game,jump-gameII
- Leetcode 贪心 Jump Game II
- Jump Game I,II 贪心
- [leetcode][贪心] Jump Game II
- Jump Game II-贪心算法
- LeetCode Jump Game II(贪心)
- 45. Jump Game II(贪心)
- LeetCode45 Jump Game II【贪心】
- 12.2 Jump Game II
- 贪心算法——jump-game
- [LeetCode]Jump Game II(贪心&&DP!!!!!)
- leetCode #45 Jump Game II 贪心
- leetcode -- Jump Game II -- 贪心,要看
- Jump Game II leetcode 45 贪心
- LeetCode 45. Jump Game II|贪心算法
- 11.2—分治法—Sqrt(x)
- 12.1—贪心法—Jump Game
- 信息系统设计师的出路有哪些?
- css 小技巧
- 在linux中安装jdk,以及linux下java环境变量的配置问题
- 12.2—贪心法—Jump Game II
- iOS中的@property的属性
- 游戏room8 第六关的答案
- 12.3—贪心法—Best Time to Buy and Sell Sto
- 系统开发团队需要什么样的专业人才?
- 12.4—贪心法—Best Time to Buy and Sell Sto II
- Echarts关系图-力引导布局
- 12.5—贪心法—Longest Substring Without Repeating Characters
- 系统开发团队如何招聘到合适的人才?