回溯算法小结

类型一:候选数组中的数可选可不选 (leetcode 40 组合总和)

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的每个数字在每个组合中只能使用一次。
输入: candidates = [10,1,2,7,6,1,5], target = 8
输出:[[1, 7],[1, 2, 5],[2, 6],[1, 1, 6]]

from typing import List

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        if len(candidates) < 1 or sum(candidates) < target:
            return []
        res = []
        self.help(candidates, target, 0, res, [])
        return res

    def help(self, candidates, target, index, res, cur_list):

        if target == 0:
            cur_list.sort()
            if cur_list not in res:
                res.append(cur_list)
            return

        if index >= len(candidates):
            return

        self.help(candidates, target, index + 1, res, cur_list)  # 不要当前候选

        if target - candidates[index] >= 0:
            self.help(candidates, target - candidates[index] , index + 1, res, cur_list+[candidates[index]])
if __name__ == '__main__':
    candidates = [10, 1, 2, 7, 6, 1, 5]
    target = 8
    a = Solution().combinationSum2(candidates, target)
    print(a)

类型二:候选数组中的数都需要选,不过选择的顺序不同(leetcode 46、全排列 )

给定一个 没有重复 数字的序列,返回其所有可能的全排列。
例如:
输入: [1,2,3]
输出:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

class Solution(object):
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        self.help(nums, res, [])
        return res

    def help(self, arr, res, cur_list):
        if len(cur_list) == len(arr):
            res.append(cur_list)
            return

        for num in arr:
            if num not in cur_list:
                self.help(arr, res, cur_list + [num])
if __name__ == '__main__':
    arr = [1, 2, 3]
    a = Solution().permute(arr)
    print(a)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值