leetcode40 組合總和 II

2021-10-07 02:44:34 字數 1462 閱讀 7438

題目:

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

candidates 中的每個數字在每個組合中只能使用一次。

說明:所有數字(包括目標數)都是正整數。

解集不能包含重複的組合。

示例 1:

輸入: candidates = [10,1,2,7,6,1,5], target = 8,

所求解集為:

[[1, 7],

[1, 2, 5],

[2, 6],

[1, 1, 6]

]

示例 2:

輸入: candidates = [2,5,2,1,2], target = 5,

所求解集為:

[[1,2,2],

[5]]

思路:回溯。

跟上一題思路基本一致,由於candidates裡的元素只能出現一次,所以每次回溯從下乙個元素開始;由於candidates有重複的元素,因此如果從重複的元素開始回溯就會出現重複,所以需要加上這塊判重的條件。

**:

class

solution

:def

combinationsum2

(self, candidates: list[

int]

, target:

int)

-> list[list[

int]]:

res =

defbacktrack

(aim, candidate, target, start)

:if target <0:

return

if target ==0:

nonlocal res

list

(aim)

)return

for i in

range

(start,

len(candidate)):

if i>start and candidate[i-1]

== candidate[i]

:continue

) backtrack(aim, candidate, target-candidate[i]

, i+1)

aim.pop(

) candidates.sort(

) backtrack(

, candidates, target,0)

return res

leetcode 40 組合總和

給定乙個陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的每個數字在每個組合中只能使用一次。說明 示例 1 輸入 candidates 10,1,2,7,6,1,5 target 8,所求解集為 1,7 1,2,...

leetcode40 組合總和 II

給定乙個陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的每個數字在每個組合中只能使用一次。說明 所有數字 包括目標數 都是正整數。解集不能包含重複的組合。示例 1 輸入 candidates 1...

LeetCode 40 組合總和 II

給定乙個陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的每個數字在每個組合中只能使用一次。說明 示例 1 輸入 candidates 10,1,2,7,6,1,5 target 8,所求解集為 1,7 1,2,...