【LeetCode】45. 跳跃游戏 II

1 问题

给定一个长度为 n 的 0 索引整数数组 nums。初始位置为 nums[0]。

每个元素 nums[i] 表示从索引 i 向前跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

0 <= j <= nums[i]
i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。

示例 1:

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

示例 2:

输入: nums = [2,3,0,1,4]
输出: 2

2 答案

自己写的,回溯算法,超出内存限制

class Solution:
    def jump(self, nums: List[int]) -> int:

        def dfs(nums, start, path, res, target):
            if start < len(nums):
                
                if target == nums[start]:
                    res.append(path)
                for i in range(1, nums[start]+1):
                    if nums[start]+i > target:
                        break
                    dfs(nums, start+nums[i], path+[nums[i]], res, target)

        path = []
        res = []
        dfs(nums, 0, path, res, len(nums))
        return len(res)

官方解,贪心算法

class Solution:
    def jump(self, nums: List[int]) -> int:
        step, end, max_bound = 0, 0, 0
        for i in range(len(nums)-1):  # 只遍历到倒数第二个元素
            max_bound = max(max_bound, nums[i]+i)  # 上一索引最远位置和当前索引最远位置的较大者
            if (i==end):
                step += 1
                end = max_bound # 逐渐接近最后一个位置
        return step

3 知识点

贪心算法
在每一步贪心选择中,只考虑当前对自己最有利的选择,而不去考虑在后面看来这种选择是否合理。

https://blog.csdn.net/weixin_49370884/article/details/126247776

你可能感兴趣的:(LeetCode,Python,leetcode,算法)