找出所有相加之和为 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]]
思路:首先边界条件肯定是k == 0 and sum(tmp) == n,这也是回溯的顶点(我把这个看做顶点),在进行搜索,每搜索的一次k-1,递归一次,tmp + 【i】
python版代码:
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)
每次写这样的题目都发现有人用python的itertools库:这个库可以直接输出一个排列组合就是leetcode77题
class Solution:
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
result = []
for i in itertools.combinations(range(1, 10), k):
if sum(i) == n:
result.append(list(i))
return result