LeetCode-----第四十五题-----跳跃游戏 II

跳跃游戏 II

难度困难595

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

示例:

输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
     从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

说明:

假设你总是可以到达数组的最后一个位置。

 

题目分析:

       就是挨个跳呗,总的想法来说是贪心算法,每次跳最大值,这样就会很麻烦,可以考虑贪心和DP相结合的想法。遍历每一个数,然后计算每个数的maxpos,然后把end记录到maxpos。然后一直走到end即可,再把maxpos赋值给end,继续走。

 

参考代码:

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <deque>
#include <stack>
#include <algorithm>
#include <map>

using namespace std;


class Solution {
public:
    //这边使用贪心加DP
	int jump(vector<int>& nums)
	{
		int ans = 0; //计数次数
		int end = 0; //跳的最大位置
		int maxPos = 0;//每一格跳的位置中最大的位置
		//如果maxPos超过末位也没事,执行到最后第二位即可,最后一位不需要跳
		for (int i = 0; i < nums.size() - 1; i++)
		{
			maxPos = max(nums[i] + i, maxPos);//对比当前位置加上当前位置上的跳数和前面最大的跳数
			if (i == end)//如果走到了前面的最大end,继续赋值最大的pos,同时进行跳数增加
			{
				end = maxPos;
				ans++;//增加跳数
			}
		}
		return ans;
	}

    //贪心算法,写的还有问题
	//int jump(vector<int>& nums) {
	//	if (nums.size() <= 1)
	//		return 0;

	//	int index = 0; 
	//	int temp_index = 0;
	//	int temp = 0;
	//	int count = 0;
	//	for (int i = index; i < nums.size(); i = index)
	//	{
	//		temp = index;
	//		temp_index = 0;
	//		int limit = i + nums[i];
	//		if (limit >= nums.size())
	//			limit = nums.size() - 1;
	//		for (int j = i + 1; j <= limit; j++)
	//		{
	//			if (j - i < nums.size() - index && temp < nums[j] + j - i)
	//			{
	//				temp = nums[j] + j - i;
	//				temp_index = j - i;
	//			}
	//		}
	//		if (temp_index != 0)
	//			index += temp_index;
	//		if (index == nums.size() - 1)
	//		{
	//			count++;
	//			return count;
	//		}
	//		count++;
	//	}
	//	return count;
	//}
};

int main()
{
	Solution solution;
	vector<int> arr = { 2,1,1,4,1,1,4 };

	cout << solution.jump(arr) << endl;

	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值