開個新欄目,每天刷刷題,簡單放一下題解。
給你一個 無重複元素 的整數數組 candidates
和一個目標整數 target
,找出 candidates
中可以使數字和爲目標數 target
的 所有 不同組合 ,並以列表形式返回。你可以按 任意順序 返回這些組合。
candidates
中的 同一個 數字可以 無限制重複被選取 。如果至少一個數字的被選數量不同,則兩種組合是不同的。
對於給定的輸入,保證和爲 target
的不同組合數少於 150
個。
示例 1:
輸入:candidates = [2,3,6,7], target = 7
輸出:[[2,2,3],[7]]
解釋:
2 和 3 可以形成一組候選,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一個候選, 7 = 7 。
僅有這兩種組合。
示例 2:
輸入: candidates = [2,3,5], target = 8
輸出: [[2,2,2,2],[2,3,3],[3,5]]
示例 3:
輸入: candidates = [2], target = 1
輸出: []
下面是題解,思路就是先排序,再用遞歸來做。
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort() # 小到大排序
res = []
def getComb(start, target, path, res):
if target == 0: # 終止條件target爲0
res.append(path[:])
return
for i in range(start, len(candidates)): # 遍歷每一個值
if candidates[i] > target: # 如果當前值大於target,直接跳出
break
path.append(candidates[i]) # 將當前值加入答案列表
getComb(i, target-candidates[i], path, res)
path.pop()
getComb(0, target, [], res)
return res