组合问题如何去重?咱就讲的明明白白

这篇可以说是全网把组合问题如何去重,讲的最清晰的一篇!

成都创新互联从2013年开始,是专业互联网技术服务公司,拥有项目网站建设、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元临海做网站,已为上家服务,为临海各地企业和个人服务,联系电话:028-86922220

组合总和II

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

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:所有数字(包括目标数)都是正整数。解集不能包含重复的组合。

示例 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.组合总和如下区别:

本题candidates 中的每个数字在每个组合中只能使用一次。

本题数组candidates的元素是有重复的,而39.组合总和是无重复元素的数组candidates

最后本题和39.组合总和要求一样,解集不能包含重复的组合。

本题的难点在于区别2中:集合(数组candidates)有重复元素,但还不能有重复的组合。

一些同学可能想了:我把所有组合求出来,再用set或者map去重,这么做很容易超时!

所以要在搜索的过程中就去掉重复组合。

很多同学在去重的问题上想不明白,其实很多题解也没有讲清楚,反正代码是能过的,感觉是那么回事,稀里糊涂的先把题目过了。

这个去重为什么很难理解呢,所谓去重,其实就是使用过的元素不能重复选取。 这么一说好像很简单!

都知道组合问题可以抽象为树形结构,那么“使用过”在这个树形结构上是有两个维度的,一个维度是同一树枝上使用过,一个维度是同一树层上使用过。没有理解这两个层面上的“使用过” 是造成大家没有彻底理解去重的根本原因。

那么问题来了,我们是要同一树层上使用过,还是同一树枝上使用过呢?

回看一下题目,元素在同一个组合内是可以重复的,怎么重复都没事,但两个组合不能相同。

所以我们要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重。

为了理解去重我们来举一个例子,candidates = [1, 1, 2], target = 3,(方便起见candidates已经排序了)

强调一下,树层去重的话,需要对数组排序!

选择过程树形结构如图所示:

组合总和II

可以看到图中,每个节点相对于 39.组合总和我多加了used数组,这个used数组下面会重点介绍。

回溯三部曲

递归函数参数

与39.组合总和套路相同,此题还需要加一个bool型数组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循环里就应该做continue的操作。

这块比较抽象,如图:

组合总和II1

我在图中将used的变化用橘黄色标注上,可以看出在candidates[i] == candidates[i - 1]相同的情况下:

  • used[i - 1] == true,说明同一树支candidates[i - 1]使用过
  • used[i - 1] == false,说明同一树层candidates[i - 1]使用过

这块去重的逻辑很抽象,网上搜的题解基本没有能讲清楚的,如果大家之前思考过这个问题或者刷过这道题目,看到这里一定会感觉通透了很多!

那么单层搜索的逻辑代码如下:

 
 
 
 
  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.组合总和的区别1:这里是i+1,每个数字在每个组合中只能使用一次
  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.             // 要对同一树层使用过的元素进行跳过
  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.组合总和的区别1,这里是i+1,每个数字在每个组合中只能使用一次
  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. };

补充

这里直接用startIndex来去重也是可以的, 就不用used数组了。

 
 
 
 
  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.             // 要对同一树层使用过的元素进行跳过
  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.组合总和的区别1,这里是i+1,每个数字在每个组合中只能使用一次
  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. };

总结

本题同样是求组合总和,但就是因为其数组candidates有重复元素,而要求不能有重复的组合,所以相对于39.组合总和难度提升了不少。

关键是去重的逻辑,代码很简单,网上一搜一大把,但几乎没有能把这块代码含义讲明白的,基本都是给出代码,然后说这就是去重了,究竟怎么个去重法也是模棱两可。

所以Carl有必要把去重的这块彻彻底底的给大家讲清楚,就连“树层去重”和“树枝去重”都是我自创的词汇,希望对大家理解有帮助!

其他语言版本

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.         //为了将重复的数字都放到一起,所以先进行排序
  7.         Arrays.sort(candidates);
  8.         //加标志数组,用来辅助判断同层节点是否已经遍历
  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.             //出现重复节点,同层的第一个节点已经被访问过,所以直接跳过
  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.             //每个节点仅能选择一次,所以从下一位开始
  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)):  #要对同一树层使用过的元素进行跳过
  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:每个数字在每个组合中只能使用一次
  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)//放入结果集
  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. }

当前名称:组合问题如何去重?咱就讲的明明白白
网站链接:http://www.hantingmc.com/qtweb/news2/155552.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联