【LeetCode】216. 组合总和 III

官方链接

找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。

说明:

所有数字都是正整数。解集不能包含重复的组合。 
示例 1:

输入: k = 3, n = 7
输出: [[1,2,4]]

示例 2:

输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]

方案:

模板

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return
    
    for 选择 in 选择列表:
        做选择
        backtrack(路径, 新的选择列表)
        撤销选择
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:

        result = []

        def dp(path, length):
            if sorted(path) not in result and len(path)==k and sum(path)==n:
                result.append(sorted(path))

            if sorted(path) in result or len(path) >= k or sum(path) >= n:
                return

            for i in range(length, 10):
                path.append(i)
                dp(path, i+1)
                path.pop()

        dp([], 1)
        return result
发布了39 篇原创文章 · 获赞 12 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/wdh315172/article/details/105106923