LeetCode练习——跳跃游戏、组合求和

本文介绍了两个算法问题的解决方案:跳跃游戏II中,通过动态规划找到到达数组最后位置的最少跳跃次数;组合求和II中,使用回溯法找出所有可能的数字组合,使得组合和为目标数。示例代码详细展示了如何实现这两个算法。
摘要由CSDN通过智能技术生成

跳跃游戏 II

题目

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

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

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

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

示例

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

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

代码

class Solution(object):
    def jump(self, nums):
        if len(nums) == 1: return 0
        ans = 0 #表示最远到达的位置
        curDistance = 0 # 参数初始化简化写法
        nextDistance = 0
        for i in range(len(nums)): #遍历nums中的每个位置
            nextDistance = max(i + nums[i], nextDistance) # 下一个跳跃位置
            if i == curDistance:
                if curDistance != len(nums) - 1:
                    ans += 1
                    curDistance = nextDistance
                    if nextDistance >= len(nums) - 1: break
        return ans

组合求和 II

题目

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
说明:
所有数字(包括target)都是正整数
解集不能包括重复的组合

示例

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

代码

class Solution(object):
    def combinationSum2(self, candidates, target): #组合求和
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        path = []
        def backtrack(candidates,target,sum,startIndex):
            if sum == target: res.append(path[:])
            for i in range(startIndex,len(candidates)): #要对同一数层使用过的元素进行跳过  
                if sum + candidates[i] > target: return 
                if i > startIndex and candidates[i] == candidates[i-1]: continue  #直接用startIndex来去重,要对同一树层使用过得元素进行跳过
                sum += candidates[i]
                path.append(candidates[i])
                backtrack(candidates,target,sum,i+1) # i+1 每个数字在每个组合中只能使用一次 
                sum -= candidates[i]  #回溯法
                path.pop()  
        candidates = sorted(candidates)  #进行排序
        backtrack(candidates,target,0,0)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值