39 組合總和

2021-10-12 00:09:50 字數 2409 閱讀 1329

給定乙個無重複元素的陣列 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]

]

1 <= candidates.length <= 30

1 <= candidates[i] <= 200

candidate 中的每個元素都是獨一無二的。

1 <= target <= 500

public list

>

combinationsum

(int

candidates,

int target)

deque

stack =

newarraydeque

<

>()

;dfs

(candidates, target, stack, list,0)

;return list;

}/**

* @param candidates 深度遍歷的陣列

* @param target 不斷變換的目標值比如 7 - 2 == 5; 5 - 2 == 3; 3 - 2 == 1; 1 - 2 == -1

* @param stack 儲存的資料結構棧 比如儲存 2 2 2 2;

*/private

void

dfs(

int[

] candidates,

int target, deque

stack, list

> list,

int begin)

if(target ==0)

//i 不能是0 不然會重複的

for(

int i = begin; i < candidates.length; i++

)}

//優化

public list

>

combinationsum

(int

candidates,

int target)

deque

stack =

newarraydeque

<

>()

;//減少遍歷的情況 前提要陣列是有序的

arrays.

sort

(candidates)

;dfs

(candidates, target, stack, list,0)

;return list;

}/**

* @param candidates 深度遍歷的陣列

* @param target 不斷變換的目標值比如 7 - 2 == 5; 5 - 2 == 3; 3 - 2 == 1; 1 - 2 == -1

* @param stack 儲存的資料結構棧 比如儲存 2 2 2 2;

*/private

void

dfs(

int[

] candidates,

int target, deque

stack, list

> list,

int begin)

*/if

(target ==0)

//i 不能是0 不然會重複的

for(

int i = begin; i < candidates.length; i++

) stack.

addlast

(candidates[i]);

//每個數都要從自己本身開始遍歷 跟我舉得例子類似 所以begin還是i

dfs(candidates, target - candidates[i]

, stack, list, i)

;//沒找到 就把剛剛加到棧裡的數拿出來 比如

//7 - 2 == 5; 5 - 2 == 3; 3 - 2 == 1; 1 - 2 == -1 把-2拿出來。

stack.

removelast()

;}}

39 組合總和

給定乙個無重複元素的陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的數字可以無限制重複被選取。說明 示例 1 輸入 candidates 2,3,6,7 target 7,所求解集為 7 2,2...

39 組合總和

給定乙個無重複元素的陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的數字可以無限制重複被選取。說明 示例 1 輸入 candidates 2,3,6,7 target 7,所求解集為 7 2,2,3 示例 2 ...

39 組合總和

給定乙個無重複元素的陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的數字可以無限制重複被選取。說明 輸入 candidates 2,3,6,7 target 7,所求解集為 7 2,2,3 輸入 candida...