天天看點

LeetCode---216. Combination Sum III

題目

給出n和k,從1到9中選出k個數,使得k個數的和為n。1到9每個數隻能使用1次。

Python題解

class Solution(object):
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        path, res = [], []
        self.dfs(k, n, , path, res)
        return res

    def dfs(self, k, n, index, path ,res):
        if k == :
            if sum(path) == n:
                res.append(path[:])
        else:
            for i in range(index, ):
                path.append(i)
                self.dfs(k - , n, i + , path, res)
                path.pop(-)