題目描述:
思路:此題採用遞迴的方法求解。畫出遞迴樹,可以得到答案給定乙個無重複元素的陣列 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]
]
![](https://pic.w3help.cc/6e0/c2e4a488708bcec011ef27297a0cd.jpeg)
當走到葉子節點是0的時候,說明已經出現了一條答案路徑,將此答案路徑新增到結果res中即可。而如果判斷出可能出現負數的葉子節點時,則停止遞迴。另外題目中說了,不允許出現重複的答案組合,這只需要在選擇節點的時候注意:上層節點的值不能大於下層節點的值即可,這個可以通過index下標來進行約束(這個需要首先對candidates陣列進行乙個sort排序)。
LeetCode 39 組合總和
給定乙個無重複元素的陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的數字可以無限制重複被選取。說明 示例 1 輸入 candidates 2,3,6,7 target 7,所求解集為 7 2,2,3 示例 2 ...
leetcode39 組合總和
參考 class solution if next num.size target num next 0 邊界條件 return 對於每個元素,有兩種處理方式,選當前元素或者不選當前元素 psol.push back num next 選當前元素 search num,next,psol,targe...
LeetCode39組合總和
給定乙個無重複元素的陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的數字可以無限制重複被選取。說明 所有數字 包括 target 都是正整數。解集不能包含重複的組合。示例 1 輸入 candid...