組合問題如何去重?咱就講的明明白白
這篇可以說是全網(wǎng)把組合問題如何去重,講的最清晰的一篇!
組合總和II
力扣題目鏈接:https://leetcode-cn.com/problems/combination-sum-ii/
給定一個數(shù)組 candidates 和一個目標數(shù) target ,找出 candidates 中所有可以使數(shù)字和為 target 的組合。
candidates 中的每個數(shù)字在每個組合中只能使用一次。
說明:所有數(shù)字(包括目標數(shù))都是正整數(shù)。解集不能包含重復(fù)的組合。
示例 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] ]
思路
這道題目和39.組合總和如下區(qū)別:
本題candidates 中的每個數(shù)字在每個組合中只能使用一次。
本題數(shù)組candidates的元素是有重復(fù)的,而39.組合總和是無重復(fù)元素的數(shù)組candidates
最后本題和39.組合總和要求一樣,解集不能包含重復(fù)的組合。
本題的難點在于區(qū)別2中:集合(數(shù)組candidates)有重復(fù)元素,但還不能有重復(fù)的組合。
一些同學(xué)可能想了:我把所有組合求出來,再用set或者map去重,這么做很容易超時!
所以要在搜索的過程中就去掉重復(fù)組合。
很多同學(xué)在去重的問題上想不明白,其實很多題解也沒有講清楚,反正代碼是能過的,感覺是那么回事,稀里糊涂的先把題目過了。
這個去重為什么很難理解呢,所謂去重,其實就是使用過的元素不能重復(fù)選取。 這么一說好像很簡單!
都知道組合問題可以抽象為樹形結(jié)構(gòu),那么“使用過”在這個樹形結(jié)構(gòu)上是有兩個維度的,一個維度是同一樹枝上使用過,一個維度是同一樹層上使用過。沒有理解這兩個層面上的“使用過” 是造成大家沒有徹底理解去重的根本原因。
那么問題來了,我們是要同一樹層上使用過,還是同一樹枝上使用過呢?
回看一下題目,元素在同一個組合內(nèi)是可以重復(fù)的,怎么重復(fù)都沒事,但兩個組合不能相同。
所以我們要去重的是同一樹層上的“使用過”,同一樹枝上的都是一個組合里的元素,不用去重。
為了理解去重我們來舉一個例子,candidates = [1, 1, 2], target = 3,(方便起見candidates已經(jīng)排序了)
強調(diào)一下,樹層去重的話,需要對數(shù)組排序!
選擇過程樹形結(jié)構(gòu)如圖所示:
組合總和II
可以看到圖中,每個節(jié)點相對于 39.組合總和我多加了used數(shù)組,這個used數(shù)組下面會重點介紹。
回溯三部曲
遞歸函數(shù)參數(shù)
與39.組合總和套路相同,此題還需要加一個bool型數(shù)組used,用來記錄同一樹枝上的元素是否使用過。
這個集合去重的重任就是used來完成的。
代碼如下:
- vector<vector<int>> result; // 存放組合集合
- vector<int> path; // 符合條件的組合
- void backtracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used) {
遞歸終止條件
與39.組合總和相同,終止條件為 sum > target 和 sum == target。
代碼如下:
- if (sum > target) { // 這個條件其實可以省略
- return;
- }
- if (sum == target) {
- result.push_back(path);
- return;
- }
sum > target 這個條件其實可以省略,因為和在遞歸單層遍歷的時候,會有剪枝的操作,下面會介紹到。
單層搜索的邏輯
這里與39.組合總和最大的不同就是要去重了。
前面我們提到:要去重的是“同一樹層上的使用過”,如果判斷同一樹層上元素(相同的元素)是否使用過了呢。
如果candidates[i] == candidates[i - 1] 并且 used[i - 1] == false,就說明:前一個樹枝,使用了candidates[i - 1],也就是說同一樹層使用過candidates[i - 1]。
此時for循環(huán)里就應(yīng)該做continue的操作。
這塊比較抽象,如圖:
組合總和II1
我在圖中將used的變化用橘黃色標注上,可以看出在candidates[i] == candidates[i - 1]相同的情況下:
- used[i - 1] == true,說明同一樹支candidates[i - 1]使用過
- used[i - 1] == false,說明同一樹層candidates[i - 1]使用過
這塊去重的邏輯很抽象,網(wǎng)上搜的題解基本沒有能講清楚的,如果大家之前思考過這個問題或者刷過這道題目,看到這里一定會感覺通透了很多!
那么單層搜索的邏輯代碼如下:
- for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
- // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過
- // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過
- // 要對同一樹層使用過的元素進行跳過
- if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
- continue;
- }
- sum += candidates[i];
- path.push_back(candidates[i]);
- used[i] = true;
- backtracking(candidates, target, sum, i + 1, used); // 和39.組合總和的區(qū)別1:這里是i+1,每個數(shù)字在每個組合中只能使用一次
- used[i] = false;
- sum -= candidates[i];
- path.pop_back();
- }
注意sum + candidates[i] <= target為剪枝操作,在39.組合總和有講解過!
回溯三部曲分析完了,整體C++代碼如下:
- class Solution {
- private:
- vector<vector<int>> result;
- vector<int> path;
- void backtracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used) {
- if (sum == target) {
- result.push_back(path);
- return;
- }
- for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
- // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過
- // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過
- // 要對同一樹層使用過的元素進行跳過
- if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
- continue;
- }
- sum += candidates[i];
- path.push_back(candidates[i]);
- used[i] = true;
- backtracking(candidates, target, sum, i + 1, used); // 和39.組合總和的區(qū)別1,這里是i+1,每個數(shù)字在每個組合中只能使用一次
- used[i] = false;
- sum -= candidates[i];
- path.pop_back();
- }
- }
- public:
- vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
- vector<bool> used(candidates.size(), false);
- path.clear();
- result.clear();
- // 首先把給candidates排序,讓其相同的元素都挨在一起。
- sort(candidates.begin(), candidates.end());
- backtracking(candidates, target, 0, 0, used);
- return result;
- }
- };
補充
這里直接用startIndex來去重也是可以的, 就不用used數(shù)組了。
- class Solution {
- private:
- vector<vector<int>> result;
- vector<int> path;
- void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
- if (sum == target) {
- result.push_back(path);
- return;
- }
- for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
- // 要對同一樹層使用過的元素進行跳過
- if (i > startIndex && candidates[i] == candidates[i - 1]) {
- continue;
- }
- sum += candidates[i];
- path.push_back(candidates[i]);
- backtracking(candidates, target, sum, i + 1); // 和39.組合總和的區(qū)別1,這里是i+1,每個數(shù)字在每個組合中只能使用一次
- sum -= candidates[i];
- path.pop_back();
- }
- }
- public:
- vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
- path.clear();
- result.clear();
- // 首先把給candidates排序,讓其相同的元素都挨在一起。
- sort(candidates.begin(), candidates.end());
- backtracking(candidates, target, 0, 0);
- return result;
- }
- };
總結(jié)
本題同樣是求組合總和,但就是因為其數(shù)組candidates有重復(fù)元素,而要求不能有重復(fù)的組合,所以相對于39.組合總和難度提升了不少。
關(guān)鍵是去重的邏輯,代碼很簡單,網(wǎng)上一搜一大把,但幾乎沒有能把這塊代碼含義講明白的,基本都是給出代碼,然后說這就是去重了,究竟怎么個去重法也是模棱兩可。
所以Carl有必要把去重的這塊徹徹底底的給大家講清楚,就連“樹層去重”和“樹枝去重”都是我自創(chuàng)的詞匯,希望對大家理解有幫助!
其他語言版本
Java
- class Solution {
- List<List<Integer>> lists = new ArrayList<>();
- Deque<Integer> deque = new LinkedList<>();
- int sum = 0;
- public List<List<Integer>> combinationSum2(int[] candidates, int target) {
- //為了將重復(fù)的數(shù)字都放到一起,所以先進行排序
- Arrays.sort(candidates);
- //加標志數(shù)組,用來輔助判斷同層節(jié)點是否已經(jīng)遍歷
- boolean[] flag = new boolean[candidates.length];
- backTracking(candidates, target, 0, flag);
- return lists;
- }
- public void backTracking(int[] arr, int target, int index, boolean[] flag) {
- if (sum == target) {
- lists.add(new ArrayList(deque));
- return;
- }
- for (int i = index; i < arr.length && arr[i] + sum <= target; i++) {
- //出現(xiàn)重復(fù)節(jié)點,同層的第一個節(jié)點已經(jīng)被訪問過,所以直接跳過
- if (i > 0 && arr[i] == arr[i - 1] && !flag[i - 1]) {
- continue;
- }
- flag[i] = true;
- sum += arr[i];
- deque.push(arr[i]);
- //每個節(jié)點僅能選擇一次,所以從下一位開始
- backTracking(arr, target, i + 1, flag);
- int temp = deque.pop();
- flag[i] = false;
- sum -= temp;
- }
- }
- }
Python
- class Solution:
- def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
- res = []
- path = []
- def backtrack(candidates,target,sum,startIndex):
- if sum == target: res.append(path[:])
- for i in range(startIndex,len(candidates)): #要對同一樹層使用過的元素進行跳過
- if sum + candidates[i] > target: return
- if i > startIndex and candidates[i] == candidates[i-1]: continue #直接用startIndex來去重,要對同一樹層使用過的元素進行跳過
- sum += candidates[i]
- path.append(candidates[i])
- backtrack(candidates,target,sum,i+1) #i+1:每個數(shù)字在每個組合中只能使用一次
- sum -= candidates[i] #回溯
- path.pop() #回溯
- candidates = sorted(candidates) #首先把給candidates排序,讓其相同的元素都挨在一起。
- backtrack(candidates,target,0,0)
- return res
Go:
主要在于如何在回溯中去重
- func combinationSum2(candidates []int, target int) [][]int {
- var trcak []int
- var res [][]int
- var history map[int]bool
- history=make(map[int]bool)
- sort.Ints(candidates)
- backtracking(0,0,target,candidates,trcak,&res,history)
- return res
- }
- func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,history map[int]bool){
- //終止條件
- if sum==target{
- tmp:=make([]int,len(trcak))
- copy(tmp,trcak)//拷貝
- *res=append(*res,tmp)//放入結(jié)果集
- return
- }
- if sum>target{return}
- //回溯
- // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過
- // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過
- for i:=startIndex;i<len(candidates);i++{
- if i>0&&candidates[i]==candidates[i-1]&&history[i-1]==false{
- continue
- }
- //更新路徑集合和sum
- trcak=append(trcak,candidates[i])
- sum+=candidates[i]
- history[i]=true
- //遞歸
- backtracking(i+1,sum,target,candidates,trcak,res,history)
- //回溯
- trcak=trcak[:len(trcak)-1]
- sum-=candidates[i]
- history[i]=false
- }
- }