216. Combination Sum III

注意剪枝条件即可

class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        
        result = []
        def dfs(start, pathlist):
            if len(pathlist) == k and sum(pathlist) == n:   # 长度条件和SUM条件
                result.append(pathlist[:])
                return
            
            for x in range(start,10):
                pathlist.append(x)
                dfs(x+1, pathlist)    # 从x+1继续
                pathlist.pop()
                
        dfs(1,[])
        return result

你可能感兴趣的:(算法题)