Skip to content

Files

Latest commit

 

History

History
65 lines (46 loc) · 1.74 KB

216-combination-sum-iii.md

File metadata and controls

65 lines (46 loc) · 1.74 KB

216. Combination Sum III - 组合总和 III

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

说明:

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

示例 1:

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

示例 2:

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

题目标签:Array / Backtracking

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 72 ms 6.5 MB
class Solution:
    def dfs(self, k, n, m, cur, res):
        if k == 0:
            if n == 0:
                res.append(cur)
        else:
            if n > 0:
                for i in range(m, 10):
                    cur.append(i)
                    self.dfs(k-1, n-i, i+1, cur[:], res)
                    cur.pop()

    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        cur = []
        res = []
        self.dfs(k, n, 1, cur, res)
        return res