給定乙個陣列candidates
和乙個目標數target
,找出candidates
中所有可以使數字和為target
的組合。
candidates
中的每個數字在每個組合中只能使用一次。
說明:
示例 1:
輸入:candidates = [10,1,2,7,6,1,5], target = 8,所求解集為:[示例 2:[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
輸入:candidates = [2,5,2,1,2], target = 5,所求解集為:[此題和39題相比,給的陣列不是順序的了,所以我們需要先進行排序。由於陣列中有重複元素,所以我們需要在每次for迴圈避免使用與上一次相同的數,相同就continue,直到不相同為止,所以要用if(i > start && candidates[i] == candidates[i - 1])來判定。此外這次規定每乙個數字在每乙個組合中只能使用一次,所以每次dfs時,要把start加1再傳進dfs函式,使得接下來的遞迴從下乙個位置的數開始。以上就是和39題的不同之處,最後返回ans結束。[1,2,2],
[5]]
class solution
void dfs(vector& candidates, int target, int start, vector& out, vector>& ans)
for(int i = start; i < candidates.size(); i++)
}};
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...
Leetcode40 組合總和 II
給定乙個陣列candidates和乙個目標數target,找出candidates中所有可以使數字和為target的組合。candidates中的每個數字在每個組合中只能使用一次。說明 示例 1 輸入 candidates 10,1,2,7,6,1,5 target 8,所求解集為 1,7 1,2,...