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.
贪心策略:在当前可跳的位置中,不是选择最远的,而是选一个可以使得下次跳得最远的。
下面的代码中,每到一个边界,不是说这次跳到这,而是相当于确定了上一次跳的位置,所以可以计数。
1) i 只能在当前可达范围reach内前移,这一性质决定了循环的上界。在这个范围移动的同时维护下一步可达范围next。
2) 当i 到达当前范围边界reach,计数。用下一步可达范围next更新reach。如果reach可达数组末尾,返回count.
3)退出循环的含义:已经走完了可达范围,并且reach没有达到数组末尾。结论就是达不到末尾,返回-1。
int jump(int A[], int n) {
if (n <= 1) return 0;
int count = 0, reach = 0, next = 0;
for (int i = 0; i <= reach; ++i) {
next = max(next,i + A[i]);
if (i == reach) {
count++;
reach = next;
if (reach >= n - 1) return count;
}
}
return -1 ;
}
Follow up: 如果以跳到末尾,打印具体跳点路径,否则返回空路径
#include <vector>
#include <iostream>
using namespace std;
vector<int> jump2(vector<int> A) {
vector<int> jumpPos;
for (int i = 0, reach = 0, jump = 0, next = 0; i <= reach; ++i) {
if (i + A[i] > next) {
jump = i;
next = i + A[i];
}
if (i == reach ) {
reach = next;
jumpPos.push_back(jump);
}
if (reach >= A.size() - 1) {
return jumpPos;
}
}
return {};
}
int main() {
vector<int> A = {1, 3, 0, 1, 0};
for (int x : jump2(A)) {
cout << x << " ";
}
cout << endl;
}
打印所有路径
#include <vector>
#include <iostream>
using namespace std;
void dfs(int i, vector<int>&A, vector<int>& path) {
if (i + A[i] >= A.size() - 1) {
for (int e : path) {
cout << e << ' ';
}
cout << endl;
}
for (int d = 1; d <= A[i] && i + d < A.size() - 1; ++d) {
path.push_back(i + d);
dfs(i + d, A, path);
path.pop_back();
}
}
void jump2(vector<int> A) {
vector<int> path = {0};
dfs(0, A, path);
}
int main() {
vector<int> A = {1, 3, 0, 1, 0};
jump2(A);
}