自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

組合問題如何去重?咱就講的明明白白

開發(fā) 前端
本題同樣是求組合總和,但就是因為其數(shù)組candidates有重復(fù)元素,而要求不能有重復(fù)的組合,所以Carl有必要把去重的這塊徹徹底底的給大家講清楚,就連“樹層去重”和“樹枝去重”都是我自創(chuàng)的詞匯,希望對大家理解有幫助!

[[425666]]

這篇可以說是全網(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來完成的。

代碼如下:

  1. vector<vector<int>> result; // 存放組合集合 
  2. vector<int> path;           // 符合條件的組合 
  3. void backtracking(vector<int>& candidates, int target, int sumint startIndex, vector<bool>& used) { 

遞歸終止條件

39.組合總和相同,終止條件為 sum > target 和 sum == target。

代碼如下:

  1. if (sum > target) { // 這個條件其實可以省略 
  2.     return
  3. if (sum == target) { 
  4.     result.push_back(path); 
  5.     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)上搜的題解基本沒有能講清楚的,如果大家之前思考過這個問題或者刷過這道題目,看到這里一定會感覺通透了很多!

那么單層搜索的邏輯代碼如下:

  1. for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) { 
  2.     // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過 
  3.     // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過 
  4.     // 要對同一樹層使用過的元素進行跳過 
  5.     if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) { 
  6.         continue
  7.     } 
  8.     sum += candidates[i]; 
  9.     path.push_back(candidates[i]); 
  10.     used[i] = true
  11.     backtracking(candidates, target, sum, i + 1, used); // 和39.組合總和的區(qū)別1:這里是i+1,每個數(shù)字在每個組合中只能使用一次 
  12.     used[i] = false
  13.     sum -= candidates[i]; 
  14.     path.pop_back(); 

注意sum + candidates[i] <= target為剪枝操作,在39.組合總和有講解過!

回溯三部曲分析完了,整體C++代碼如下:

  1. class Solution { 
  2. private: 
  3.     vector<vector<int>> result; 
  4.     vector<int> path; 
  5.     void backtracking(vector<int>& candidates, int target, int sumint startIndex, vector<bool>& used) { 
  6.         if (sum == target) { 
  7.             result.push_back(path); 
  8.             return
  9.         } 
  10.         for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) { 
  11.             // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過 
  12.             // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過 
  13.             // 要對同一樹層使用過的元素進行跳過 
  14.             if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) { 
  15.                 continue
  16.             } 
  17.             sum += candidates[i]; 
  18.             path.push_back(candidates[i]); 
  19.             used[i] = true
  20.             backtracking(candidates, target, sum, i + 1, used); // 和39.組合總和的區(qū)別1,這里是i+1,每個數(shù)字在每個組合中只能使用一次 
  21.             used[i] = false
  22.             sum -= candidates[i]; 
  23.             path.pop_back(); 
  24.         } 
  25.     } 
  26.  
  27. public
  28.     vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { 
  29.         vector<bool> used(candidates.size(), false); 
  30.         path.clear(); 
  31.         result.clear(); 
  32.         // 首先把給candidates排序,讓其相同的元素都挨在一起。 
  33.         sort(candidates.begin(), candidates.end()); 
  34.         backtracking(candidates, target, 0, 0, used); 
  35.         return result; 
  36.     } 
  37. }; 

補充

這里直接用startIndex來去重也是可以的, 就不用used數(shù)組了。

  1. class Solution { 
  2. private: 
  3.     vector<vector<int>> result; 
  4.     vector<int> path; 
  5.     void backtracking(vector<int>& candidates, int target, int sumint startIndex) { 
  6.         if (sum == target) { 
  7.             result.push_back(path); 
  8.             return
  9.         } 
  10.         for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) { 
  11.             // 要對同一樹層使用過的元素進行跳過 
  12.             if (i > startIndex && candidates[i] == candidates[i - 1]) { 
  13.                 continue
  14.             } 
  15.             sum += candidates[i]; 
  16.             path.push_back(candidates[i]); 
  17.             backtracking(candidates, target, sum, i + 1); // 和39.組合總和的區(qū)別1,這里是i+1,每個數(shù)字在每個組合中只能使用一次 
  18.             sum -= candidates[i]; 
  19.             path.pop_back(); 
  20.         } 
  21.     } 
  22.  
  23. public
  24.     vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { 
  25.         path.clear(); 
  26.         result.clear(); 
  27.         // 首先把給candidates排序,讓其相同的元素都挨在一起。 
  28.         sort(candidates.begin(), candidates.end()); 
  29.         backtracking(candidates, target, 0, 0); 
  30.         return result; 
  31.     } 
  32. }; 

總結(jié)

本題同樣是求組合總和,但就是因為其數(shù)組candidates有重復(fù)元素,而要求不能有重復(fù)的組合,所以相對于39.組合總和難度提升了不少。

關(guān)鍵是去重的邏輯,代碼很簡單,網(wǎng)上一搜一大把,但幾乎沒有能把這塊代碼含義講明白的,基本都是給出代碼,然后說這就是去重了,究竟怎么個去重法也是模棱兩可。

所以Carl有必要把去重的這塊徹徹底底的給大家講清楚,就連“樹層去重”和“樹枝去重”都是我自創(chuàng)的詞匯,希望對大家理解有幫助!

其他語言版本

Java

  1. class Solution { 
  2.     List<List<Integer>> lists = new ArrayList<>(); 
  3.     Deque<Integer> deque = new LinkedList<>(); 
  4.     int sum = 0; 
  5.  
  6.     public List<List<Integer>> combinationSum2(int[] candidates, int target) { 
  7.         //為了將重復(fù)的數(shù)字都放到一起,所以先進行排序 
  8.         Arrays.sort(candidates); 
  9.         //加標志數(shù)組,用來輔助判斷同層節(jié)點是否已經(jīng)遍歷 
  10.         boolean[] flag = new boolean[candidates.length]; 
  11.         backTracking(candidates, target, 0, flag); 
  12.         return lists; 
  13.     } 
  14.  
  15.     public void backTracking(int[] arr, int target, int index, boolean[] flag) { 
  16.         if (sum == target) { 
  17.             lists.add(new ArrayList(deque)); 
  18.             return
  19.         } 
  20.         for (int i = index; i < arr.length && arr[i] + sum <= target; i++) { 
  21.             //出現(xiàn)重復(fù)節(jié)點,同層的第一個節(jié)點已經(jīng)被訪問過,所以直接跳過 
  22.             if (i > 0 && arr[i] == arr[i - 1] && !flag[i - 1]) { 
  23.                 continue
  24.             } 
  25.             flag[i] = true
  26.             sum += arr[i]; 
  27.             deque.push(arr[i]); 
  28.             //每個節(jié)點僅能選擇一次,所以從下一位開始 
  29.             backTracking(arr, target, i + 1, flag); 
  30.             int temp = deque.pop(); 
  31.             flag[i] = false
  32.             sum -= temp
  33.         } 
  34.     } 

Python

  1. class Solution: 
  2.     def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 
  3.         res = [] 
  4.         path = [] 
  5.         def backtrack(candidates,target,sum,startIndex): 
  6.             if sum == target: res.append(path[:]) 
  7.             for i in range(startIndex,len(candidates)):  #要對同一樹層使用過的元素進行跳過 
  8.                 if sum + candidates[i] > target: return 
  9.                 if i > startIndex and candidates[i] == candidates[i-1]: continue  #直接用startIndex來去重,要對同一樹層使用過的元素進行跳過 
  10.                 sum += candidates[i] 
  11.                 path.append(candidates[i]) 
  12.                 backtrack(candidates,target,sum,i+1)  #i+1:每個數(shù)字在每個組合中只能使用一次 
  13.                 sum -= candidates[i]  #回溯 
  14.                 path.pop()  #回溯 
  15.         candidates = sorted(candidates)  #首先把給candidates排序,讓其相同的元素都挨在一起。 
  16.         backtrack(candidates,target,0,0) 
  17.         return res 

Go:

主要在于如何在回溯中去重

  1. func combinationSum2(candidates []int, target int) [][]int { 
  2.     var trcak []int 
  3.     var res [][]int 
  4.     var history map[int]bool 
  5.     history=make(map[int]bool) 
  6.     sort.Ints(candidates) 
  7.     backtracking(0,0,target,candidates,trcak,&res,history) 
  8.     return res 
  9. func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,history map[int]bool){ 
  10.     //終止條件 
  11.     if sum==target{ 
  12.         tmp:=make([]int,len(trcak)) 
  13.         copy(tmp,trcak)//拷貝 
  14.         *res=append(*res,tmp)//放入結(jié)果集 
  15.         return 
  16.     } 
  17.     if sum>target{return
  18.     //回溯 
  19.     // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過 
  20.     // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過 
  21.     for i:=startIndex;i<len(candidates);i++{ 
  22.         if i>0&&candidates[i]==candidates[i-1]&&history[i-1]==false
  23.                 continue 
  24.         } 
  25.         //更新路徑集合和sum 
  26.         trcak=append(trcak,candidates[i]) 
  27.         sum+=candidates[i] 
  28.         history[i]=true 
  29.         //遞歸 
  30.         backtracking(i+1,sum,target,candidates,trcak,res,history) 
  31.         //回溯 
  32.         trcak=trcak[:len(trcak)-1] 
  33.         sum-=candidates[i] 
  34.         history[i]=false 
  35.     } 

 

責任編輯:姜華 來源: 代碼隨想錄
相關(guān)推薦

2010-09-06 17:35:03

PPPOE配置

2020-02-10 19:42:01

CPIP 協(xié)議,

2011-11-04 16:49:26

Action BarAndroid

2011-04-27 17:05:39

2010-10-08 15:05:00

無線路由設(shè)置

2012-02-20 21:59:08

無線路由設(shè)置

2021-09-30 09:59:23

OSPF網(wǎng)絡(luò)協(xié)議網(wǎng)絡(luò)技術(shù)

2021-02-23 08:10:18

Nginx反向代理負載均衡器

2010-06-29 14:38:14

Linux服務(wù)器

2010-08-03 09:17:00

2010-07-05 15:33:49

2010-09-09 09:52:03

Linux服務(wù)器

2010-07-14 09:55:12

2010-08-25 09:09:58

2010-10-15 10:01:19

無線網(wǎng)絡(luò)構(gòu)建

2013-05-23 11:16:28

大數(shù)據(jù)技術(shù)大數(shù)據(jù)AdTime

2010-01-13 17:07:21

防輻射機箱選購

2010-08-06 10:00:05

負載均衡

2020-11-18 09:25:39

Docker

2020-12-22 10:57:36

DockerLinux程序員
點贊
收藏

51CTO技術(shù)棧公眾號