leetcode45.跳跃游戏 II

1.题目
给定一个非负整数数组,你最初位于数组的第一个位置。数组中的每个元素代表你在该位置可以跳跃的最大长度。你的目标是使用最少的跳跃次数到达数组的最后一个位置。
2.示例
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
3.思路
倒推
动态规划
4.代码
a.

int jump(vector<int>& nums) {
	int cur=nums.size()-1;
	if(cur==0) return 0;
	int res=0;
	while(1){
	int pre=cur;
	for(int i=cur-1;i>=0;i--){
		if(i+nums[i]>=pre)
			if(cur>i) cur=i;
			}
	res++;
	if(cur==0) return res;
	}
}

//可能会超出时间限制,对元素个数比较大的数组可以直接用贪心算法。
b.

猜你喜欢

转载自blog.csdn.net/qq_14962179/article/details/86133343
今日推荐