leetcode 39 組合總和(回溯)

2021-09-24 16:40:01 字數 1637 閱讀 3080

給定乙個無重複元素的陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。

candidates中的數字可以無限制重複被選取

說明:

示例 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中的數字可以無限制重複被選取,並且需要把組合都列印出來,所以我們考慮用回溯方法求解。

(1)我們定義了乙個回溯函式combinationsumcore(vector& candidates, int target, int begin, vector& curr, vector>& ret),其中begin表示使用字典中元素的起始位置(這樣組合的陣列元素都是從小到大排列的,避免出現(2,3,3)(3,2,3)這樣重複元素構成的組合)。並且用curr來儲存當前的組合。ret儲存所有的組合。

(2)當target==0時,表明找到一組解,將curr寫入ret

target<0,表明當前curr陣列和大於target,彈出尾元素,並繼續遞迴;

target>0target-candidates[i]作為新target,遞迴。

class

solution

void

combinationsumcore

(vector<

int>

& candidates,

int target,

int begin, vector<

int>

& curr, vector

int>>

& ret)

else

if(target<0)

// curr和大於target

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...