找出所有相加之和爲 n
的 k
個數的組合,且滿足下列條件:
- 只使用數字1到9
- 每個數字 最多使用一次
返回 所有可能的有效組合的列表 。該列表不能包含相同的組合兩次,組合可以以任何順序返回。
示例 1:
輸入: k = 3, n = 7
輸出: [[1,2,4]]
解釋:
1 + 2 + 4 = 7
沒有其他符合的組合了。
示例 2:
輸入: k = 3, n = 9
輸出: [[1,2,6], [1,3,5], [2,3,4]]
解釋:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
沒有其他符合的組合了。
示例 3:
輸入: k = 4, n = 1
輸出: []
解釋: 不存在有效的組合。
在[1,9]範圍內使用4個不同的數字,我們可以得到的最小和是1+2+3+4 = 10,因爲10 > 1,沒有有效的組合。
提示:
2 <= k <= 9
1 <= n <= 60
和上一道題大同小異,不過這裏是1~9的candidate數組,以及不能重複,每個組合的數字個數是給定的。
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
res = []
if k > n:
return res
def getComb(start, target, path):
if target == 0 and len(path) == k:
res.append(path[:])
return
for i in range(start, 10):
if i > target: # 當前值大於target,直接跳出
break
path.append(i) # 當前值加入組合列表
getComb(i+1, target-i, path) # 從後一個值開始尋找結果
path.pop()
getComb(1, n, [])
return res