Leetcode: Subsets II

本文介绍了一种使用深度优先搜索(DFS)算法解决含有重复元素集合的所有可能子集问题的方法。通过加入检查子集是否重复的条件,确保了最终结果中不包含重复的子集。对于输入如[1,2,2]的情况,提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Given a collection of integers that might contain duplicates, S, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

 

For example,
If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解法一:
同样可以使用DFS,只不过多了一个判断条件,subset是否重复
 1 class Solution {
 2 public:
 3     vector<vector<int> >result;
 4     vector<int> s;
 5     int n;
 6 
 7     void dfs(vector<int> temp,int num){
 8         if( num == n){
 9             if(find(result.begin(),result.end(),temp) == result.end())
10                 result.push_back(temp);
11             return;
12         }
13 
14         dfs(temp,num+1);
15 
16         temp.push_back(s[num]);
17         dfs(temp,num+1);
18 
19     }
20     vector<vector<int> > subsetsWithDup(vector<int> &S) {
21         sort(S.begin(),S.end());
22 
23         result.clear();
24         vector<int> temp;
25 
26         s = S;
27         n = S.size();
28         dfs(temp,0);
29 
30         return result;
31     }
32 };

 



转载于:https://www.cnblogs.com/caijinlong/archive/2013/04/29/3050790.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值