难度中等985
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: 2
//递归+备忘录
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
int dp[10000] = { 0 };
int solve(vector<int>& nums, int p) {
//返回从p到最后需要的最小步数
if (p >= nums.size() - 1)return 0;
if (dp[p])return dp[p];
int k = nums[p];
int minn = 9999999;
for (int i = 1; i <= k; ++i) {
minn = min(solve(nums, p + i), minn);
}
return dp[p] = minn + 1;
}
int jump(vector<int>& nums) {
return solve(nums, 0);
}
};
int main()
{
int n;
vector<int> nums;
while (cin >> n) {
nums.push_back(n);
}
Solution ans;
cout<<ans.jump(nums);
return 0;
}
//贪心,记录每次走的最远,下一次记录上一次最远之前的步子中能跳最远,
//即一步最远跳多少,两步多少,。。。
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
int jump(vector<int>& nums) {
int farthest = 0,step = 0;
for (int i = 0; i < nums.size() - 1; ++i) {
int t = max(farthest, i + nums[i]);
if (i >= farthest) {
step++;
farthest = t;
}
}
return step;
}
};
int main()
{
int n;
vector<int> nums;
while (cin >> n) {
nums.push_back(n);
}
Solution ans;
cout<<ans.jump(nums);
return 0;
}