找出所有相加之和为 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]]
class Solution:
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
self.ans = []
self.robot(0,[],k,n)
return self.ans
def robot(self,idx,tmp,k,n):
if k == 0 and sum(tmp) == n:
self.ans.append(tmp[:])
for i in range(idx + 1,10):
if i not in tmp:
self.robot(i,tmp + [i],k-1,n)
执行用时: 52 ms, 在Combination Sum III的Python3提交中击败了49.37% 的用户