找出所有相加之和为 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]]
解题思路
这个问题是之前问题的衍生,而且比之前的问题容易,我们只要在原有的基础上稍加修改即可。
Leetcode 40:组合总和 II(最详细的解法!!!)
class Solution:
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
result = list()
self._combinationSum3(n, 1, list(), result, k)
return result
def _combinationSum3(self, target, index, path, res, k):
if target == 0 and len(path) == k:
res.append(path)
return
if path and target < path[-1]:
return
for i in range(index, 10):
self._combinationSum3(target-i, i + 1, path+[i], res, k)
我们仅仅增加了一个len(path) == k
。
同样的,对于递归可以解决的问题,我们都应该思考是不是可以通过迭代解决。
class Solution:
def combinationSum3(self, k, n):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
stack = [(1, list(), n)]
while stack:
i, path, remain = stack.pop()
while i < 10:
if path and remain < path[-1]:
break
if i == remain and len(path) == k - 1: # add
result.append(path + [i])
stack += [(i + 1, path + [i], remain - i)]
i+=1
return result
同样也只是一点小小的修改。
这个问题有一个非常pythonic
的解法,使用itertools.combinations
class Solution(object):
def combinationSum3(self, k, n):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
return [x for x in itertools.combinations(range(1, 10), k) if sum(x) == n]
当然我们这里也可以写出基于combinations
的版本,大家可以试试!!!
我将该问题的其他语言版本添加到了我的GitHub Leetcode
如有问题,希望大家指出!!!