2021-05-22 跳跃游戏 动归,贪心

这篇博客探讨了两种解决跳跃游戏II问题的方法:递归+备忘录和贪心算法。递归+备忘录策略通过动态规划求解最小跳跃次数,而贪心策略则通过每次跳跃尽可能远来优化步数。两种方法都在C++中进行了实现,并在给定的示例输入上运行。博客着重于算法的理解和效率比较。
摘要由CSDN通过智能技术生成

45. 跳跃游戏 II

难度中等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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值