Leetcode045 jump-game-ii

跳跃游戏 II

题目描述:

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

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

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

示例

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

说明:

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


解题思路:

主要利用贪心算法的动态规划来解决问题

  • 我们核心思想是尽可能多的跳跃到更远的地方,以来减少跳跃的次数,如果跳了一次之后还不能到,就需要多跳一次
  • 首先创建三个参数counter表示跳跃的次数,curr_end表示当前起跳点的位置的下标,curr_farthest表示当前起跳点可以跳的最远位置的下标
  • 然后通过curr_farthest = max(curr_farthest, i + nums[i])来更新最远位置的下标,然后等到i遍历到起跳点的时候,如果此时还不是到最后,那就用最贪心的方式,从起跳点跳最远距离curr_farthest,直到我们到达终点

Python源码:

from typing import List

class Solution:
    def jump(self, nums: List[int]) -> int:
        counter = 0  # 移动次数
        curr_end = 0  # 当前跳跃的终点
        curr_farthest = 0  # 最远位置的下标
        for i in range(len(nums) - 1):
            curr_farthest = max(curr_farthest, i + nums[i])
            if i == curr_end:
                counter += 1
                curr_end = curr_farthest
        return counter
        

欢迎关注我的github:https://github.com/UESTCYangHR

猜你喜欢

转载自blog.csdn.net/dzkdyhr1208/article/details/89372711