题目:
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。 说明: 所有数字都是正整数。 解集不能包含重复的组合。
思路:
这种情况下使用递归
程序:
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result = []
candidates = [1,2,3,4,5,6,7,8,9]
def auxiliary(counter, start, tmp, remain):
if remain < 0 or counter > k:
return
elif remain == 0 and counter == k:
result.append(tmp)
else:
for index in range(start, len(candidates) + 1):
if index > remain:
break
else:
auxiliary(counter + 1, index + 1, tmp + [index], remain - index)
auxiliary(0, 1, [], n)
return result