随笔- 509  文章- 0  评论- 151  阅读- 22万 

Subsets II

2013.12.27 02:47

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],
  []
]

Solution:

  This problem is a variation from the problem "Subsets". This time the set can contain some duplicates, actually a "multiset".

  My solution is stil by DFS. It doesn't seem to matter if the given data set is a strict set or multiset.

  Time complexity is O(2^n), space complexity is O(n), where n is the number of elements in the set.

Accepted code:

复制代码
 1 // 1RE, 1AC, good~
 2 #include <algorithm>
 3 #include <vector>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     vector<vector<int> > subsetsWithDup(vector<int> &S) {
 9         // IMPORTANT: Please reset any member data you declared, as
10         // the same Solution instance will be reused for each test case.
11         int i, j, n;
12         
13         n = result.size();
14         for(i = 0; i < n; ++i){
15             result[i].clear();
16         }
17         result.clear();
18         
19         sort(S.begin(), S.end());
20         n = S.size();
21         num.clear();
22         count.clear();
23         i = 0;
24         while(i < n){
25             j = i + 1;
26             while(j < n && S[i] == S[j]){
27                 ++j;
28             }
29             num.push_back(S[i]);
30             count.push_back(j - i);
31             i = j;
32         }
33         n = num.size();
34         arr.clear();
35         dfs(0, n);
36         
37         return result;
38     }
39 private:
40     vector<int> num;
41     vector<int> count;
42     vector<vector<int>> result;
43     vector<int> arr;
44     
45     void dfs(int idx, int n) {
46         if(idx == n){
47             result.push_back(arr);
48             // 1RE here, stop $idx from going out of range.
49             return;
50         }
51         
52         int i, j;
53         for(i = 0; i <= count[idx]; ++i){
54             for(j = 0; j < i; ++j){
55                 arr.push_back(num[idx]);
56             }
57             dfs(idx + 1, n);
58             for(j = 0; j < i; ++j){
59                 arr.pop_back();
60             }
61         }
62     }
63 };
复制代码

 

 posted on   zhuli19901106  阅读(426)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示