原題地址39. 組合總和
給定一個無重複元素的數組 candidates
和一個目標數 target
,找出 candidates
中所有可以使數字和爲 target
的組合。
candidates
中的數字可以無限制重複被選取。
說明:
- 所有數字(包括
target
)都是正整數。 - 解集不能包含重複的組合。
示例 1:
輸入: candidates = [2,3,6,7], target = 7,
所求解集爲:
[[7], [2,2,3]]
示例 2:
輸入: candidates = [2,3,5], target = 8,
所求解集爲:
[[2,2,2,2], [2,3,3], [3,5]]
算法
迭代,先對candidates從小到大排序,每次用target減去candidates[i],如果結果剛好爲0,就輸出;如果結果小於0,說明已經溢出了,結束;如果結果大於0,那麼將candidates[i]記錄進結果,並更新target,以及candidates更改爲不小於candidates[i]的部分,保證選出的結果不重複。
代碼
class Solution:
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
def back(lst, tg, res):
for i in range(len(lst)):
if tg - lst[i] == 0:
yield res + [lst[i]]
if tg - lst[i] > 0:
yield from back(lst[i:], tg - lst[i], res + [lst[i]])
if tg - lst[i] < 0:
break
return list(back(candidates, target, []))