給定乙個陣列 candidates 和乙個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8,比如candidates=[1,2,2,2,5],target=5,當使用遞迴時,遍歷第乙個數得到組合[1],因為[1]小於target,所以繼續遞迴,遞迴遍歷[2,2,2,5],可能得到的組合為[1,2],[1,2],[1,2],[1,5],這裡第二次遞迴遍歷的時候[1,2]重複出現了三次,所以這裡需要進行去重操作,使用的操作為:所求解集為:
[[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
if candidates[i]==candidates[i-1]:continue
這樣就實現了對後面兩個[1,2]的去重。
當得到第二次得到的遍歷組合[1,2]時,因為[1,2]小於target,因此需要執行第三次遞迴,對[2,2,5]進行遍歷,可能得到的組合數為[1,2,2],[1,2,2],[1,2,5],這裡也存在重複組合,所以同樣需要進行去重操作,具體去重原理和上面介紹的一樣。
其python3**如下:
class
solution
:def
__init__
(self)
: self.ans =
defcombinationsum2
(self, candidates: list[
int]
, target:
int)
-> list[list[
int]]:
ifnot candidates:
return
candidates.sort(
)# 先進行排序;
defconbsum
(target,i,temp)
:if target ==0:
# 遞迴停止條件:]
)for n in
range
(i,len
(candidates)):
# 遍歷candidates中剩下的數字
if target-candidates[n]
<0:
break
if n>i and candidates[n]
==candidates[n-1]
:# 去重操作
continue
) conbsum(target-candidates[n]
,n+1
,temp)
temp.pop(
)# 回溯
conbsum(target,0,
)return self.ans
其c++**如下:
class
solution
} vectorint>>
combinationsum2
(vector<
int>
& candidates,
int target)
return ans;}}
;
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,...