【力扣】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]]

来源:力扣(LeetCode)

算法思路

标准回溯算法 · 改。

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        ls=list(range(1,10))
        def helper(ls,k,n,tp=[]):
            if len(tp)==k and sum(tp)==n:
                res.append(tp)
            for i in range(len(ls)):
                if sum(tp)>n:return
            helper(ls[i+1:],k,n,tp+[ls[i]])
        res=[]
        helper(ls,k,n)
        return res

修改部分两点:

                if sum(tp)>n:return

用于剪枝

        helper(ls[i+1:],k,n,tp+[ls[i]])

组合排序这里不存在逆序。

执行用时 :32 ms, 在所有 Python3 提交中击败了93.17%的用户
内存消耗 :13.8 MB, 在所有 Python3 提交中击败了100.00%的用户

你可能感兴趣的:(力扣日记)