1
+ /*
2
+ The problem is to generate all the possible subsets of the given input vector and should not print any duplicate elements.
3
+
4
+
5
+ Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
6
+
7
+ The solution set must not contain duplicate subsets. Return the solution in any order.
8
+
9
+ Example 1:
10
+
11
+ Input: nums = [1,2,2]
12
+ Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
13
+ Example 2:
14
+
15
+ Input: nums = [0]
16
+ Output: [[],[0]]
17
+
18
+ The problem is given below
19
+ https://leetcode.com/problems/subsets-ii/
20
+
21
+ Below is the recursive appraoch of the problem-
22
+ */
23
+
24
+
25
+ #include < bits/stdc++.h> // input of the header files
26
+ using namespace std ;
27
+ set<vector<int >> s; // declaing a set to store only the unique elements
28
+ void solve (vector<int > input, vector<int > & output) // recursive function to generate the unique subsets
29
+ {
30
+ if (input.size ()==0 )
31
+ {
32
+ vector<int > sum; // declaring a vector to store the combinations of the elements
33
+ sort (output.begin (),output.end ()); // sorting it to make prevent duplicates entering the set
34
+ for (auto it: output)
35
+ sum.push_back (it);
36
+ s.insert (sum); // inserting the unique elements in the set
37
+ return ; // return to end the function
38
+ }
39
+ vector<int > out1=output; // declaring a vector to store the elements of the subset
40
+ vector<int > out2=output; // declaring another vector to store the elements of the subset
41
+
42
+ out2.push_back (input[0 ]); // inserting the first element in the second vector
43
+ input.erase (input.begin ()+0 ); // erase function to delete the first element of the vector
44
+ solve (input,out1); // recursive call to generate the subsets with the first vector
45
+ solve (input,out2); // recursive call to generate the subsets with the second vector
46
+ }
47
+ vector<vector<int >> subsetsWithDup (vector<int >& nums) { // function which call the solve function to generate the subsets
48
+ vector<int > output;
49
+ solve (nums, output);
50
+ vector<vector<int >> out;
51
+ for (auto it:s)
52
+ {
53
+ out.push_back (it);
54
+ }
55
+
56
+ return out; // returning the subsets after duplicates are removed
57
+ }
58
+ int main ()
59
+ {
60
+ int t=0 ;
61
+ cin>>t;
62
+ while (t--) {
63
+ int n=0 ; // input of the vector length
64
+ cin>>n;
65
+ vector<int >nums (n);
66
+ for (int i=0 ;i<n;i++) {
67
+ cin>>nums[i];
68
+ }
69
+ vector<vector<int >> out=subsetsWithDup (nums);
70
+
71
+ // printing the output vector
72
+ for (auto it:out) {
73
+ for (auto it1:it) {
74
+ cout<<it1<<" " ;
75
+ }
76
+ cout<<endl;
77
+ }
78
+ cout<<endl;
79
+ }
80
+ }
0 commit comments