日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
組合問題如何去重?咱就講的明明白白

這篇可以說是全網(wǎng)把組合問題如何去重,講的最清晰的一篇!

成都創(chuàng)新互聯(lián)從2013年開始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項目網(wǎng)站建設(shè)、成都網(wǎng)站建設(shè)網(wǎng)站策劃,項目實施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元臨海做網(wǎng)站,已為上家服務(wù),為臨海各地企業(yè)和個人服務(wù),聯(lián)系電話:028-86922220

組合總和II

力扣題目鏈接:https://leetcode-cn.com/problems/combination-sum-ii/

給定一個數(shù)組 candidates 和一個目標(biāo)數(shù) target ,找出 candidates 中所有可以使數(shù)字和為 target 的組合。

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

說明:所有數(shù)字(包括目標(biāo)數(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)排序了)

強(qiáng)調(diào)一下,樹層去重的話,需要對數(shù)組排序!

選擇過程樹形結(jié)構(gòu)如圖所示:

組合總和II

可以看到圖中,每個節(jié)點相對于 39.組合總和我多加了used數(shù)組,這個used數(shù)組下面會重點介紹。

回溯三部曲

遞歸函數(shù)參數(shù)

與39.組合總和套路相同,此題還需要加一個bool型數(shù)組used,用來記錄同一樹枝上的元素是否使用過。

這個集合去重的重任就是used來完成的。

代碼如下:

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

遞歸終止條件

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

代碼如下:

 
 
 
 
  1. if (sum > target) { // 這個條件其實可以省略
  2.     return;
  3. }
  4. if (sum == target) {
  5.     result.push_back(path);
  6.     return;
  7. }

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的變化用橘黃色標(biāo)注上,可以看出在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.     // 要對同一樹層使用過的元素進(jìn)行跳過
  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();
  15. }

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

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

 
 
 
 
  1. class Solution {
  2. private:
  3.     vector> result;
  4.     vector path;
  5.     void backtracking(vector& candidates, int target, int sum, int startIndex, vector& 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.             // 要對同一樹層使用過的元素進(jìn)行跳過
  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. public:
  27.     vector> combinationSum2(vector& candidates, int target) {
  28.         vector used(candidates.size(), false);
  29.         path.clear();
  30.         result.clear();
  31.         // 首先把給candidates排序,讓其相同的元素都挨在一起。
  32.         sort(candidates.begin(), candidates.end());
  33.         backtracking(candidates, target, 0, 0, used);
  34.         return result;
  35.     }
  36. };

補(bǔ)充

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

 
 
 
 
  1. class Solution {
  2. private:
  3.     vector> result;
  4.     vector path;
  5.     void backtracking(vector& candidates, int target, int sum, int 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.             // 要對同一樹層使用過的元素進(jìn)行跳過
  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. public:
  23.     vector> combinationSum2(vector& candidates, int target) {
  24.         path.clear();
  25.         result.clear();
  26.         // 首先把給candidates排序,讓其相同的元素都挨在一起。
  27.         sort(candidates.begin(), candidates.end());
  28.         backtracking(candidates, target, 0, 0);
  29.         return result;
  30.     }
  31. };

總結(jié)

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

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

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

其他語言版本

Java

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

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)):  #要對同一樹層使用過的元素進(jìn)行跳過
  8.                 if sum + candidates[i] > target: return
  9.                 if i > startIndex and candidates[i] == candidates[i-1]: continue  #直接用startIndex來去重,要對同一樹層使用過的元素進(jìn)行跳過
  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. }
  10. func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,history map[int]bool){
  11.     //終止條件
  12.     if sum==target{
  13.         tmp:=make([]int,len(trcak))
  14.         copy(tmp,trcak)//拷貝
  15.         *res=append(*res,tmp)//放入結(jié)果集
  16.         return
  17.     }
  18.     if sum>target{return}
  19.     //回溯
  20.     // used[i - 1] == true,說明同一樹支candidates[i - 1]使用過
  21.     // used[i - 1] == false,說明同一樹層candidates[i - 1]使用過
  22.     for i:=startIndex;i
  23.         if i>0&&candidates[i]==candidates[i-1]&&history[i-1]==false{
  24.                 continue
  25.         }
  26.         //更新路徑集合和sum
  27.         trcak=append(trcak,candidates[i])
  28.         sum+=candidates[i]
  29.         history[i]=true
  30.         //遞歸
  31.         backtracking(i+1,sum,target,candidates,trcak,res,history)
  32.         //回溯
  33.         trcak=trcak[:len(trcak)-1]
  34.         sum-=candidates[i]
  35.         history[i]=false
  36.     }
  37. }

網(wǎng)頁名稱:組合問題如何去重?咱就講的明明白白
文章路徑:http://www.dlmjj.cn/article/dpihedp.html