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.)

#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] << " ";}}

原创粉丝点击