天天看点

Python描述 LeetCode 40. 组合总和 II

Python描述 LeetCode 40. 组合总和 II

  大家好,我是亓官劼(qí guān jié ),在【亓官劼】公众号、GitHub、B站等平台分享一些技术博文,主要包括前端开发、python后端开发、小程序开发、数据结构与算法、docker、Linux常用运维、NLP等相关技术博文,时光荏苒,未来可期,加油~

  如果喜欢博主的文章可以关注博主的个人公众号【亓官劼】(qí guān jié),里面的文章更全更新更快。如果有需要找博主的话可以在公众号后台留言,我会尽快回复消息.

本文原创为【亓官劼】(qí guān jié ),请大家支持原创,部分平台一直在恶意盗取博主的文章!!! 全部文章请关注微信公众号【亓官劼】。

题目

给定一个候选人编号的集合 ​

​candidates​

​​ 和一个目标数 ​

​target​

​​ ,找出 ​

​candidates​

​​ 中所有可以使数字和为 ​

​target​

​ 的组合。

​candidates​

​ 中的每个数字在每个组合中只能使用 一次 。

**注意:**解集不能包含重复的组合。

示例 1:

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

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]      
  • ​1 <= candidates.length <= 100​

  • ​1 <= candidates[i] <= 50​

  • ​1 <= target <= 30​

Python描述

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        if target == 0:
            return []
        res = set()
        combine = []
        freq = sorted(collections.Counter(candidates).items())

        def dfs(idx, rest):
            nonlocal combine
            if rest == 0:
                res.add(tuple(combine))
                return
            # 一个也拿不了,直接返回
            if idx == len(freq) or rest < freq[idx][0]:
                return

            # 跳过,不要这个数
            dfs(idx + 1, rest)

            # 要这个数,可以要1-freq[idx][1]个
            tmp_num = freq[idx][0]
            for i in range(1, freq[idx][1] + 1):
                combine.append(tmp_num)
                dfs(idx + 1, rest - tmp_num*i)
            combine = combine[:-freq[idx][1]]
        dfs(0, target)
        return [_ for _ in res]