Given an array arr[] of integers of size N that might contain duplicates, the task is to find all possible unique subsets, using C++ STL.
Note: Each subset should be sorted.
Examples:
Input: N = 3, arr[] = {2, 1, 2}
Output:(), (1), (1 2), (1 2 2), (2), (2 2)
Explanation: All possible subsets = (), (2), (1), (1, 2), (2), (2 2), (2 1), (2, 1, 2)
After Sorting each subset = (), (2), (1), (1, 2), (2), (2, 2), (1, 2), (1, 2, 2)
Unique Subsets in Lexicographical order = (), (1), (1, 2), (1, 2, 2), (2), (2, 2)Input: N = 4, arr[] = {1, 2, 3, 3}
Output: (), (1), (1 2), (1 2 3)
(1 2 3 3), (1 3), (1 3 3), (2), (2 3)
(2 3 3), (3), (3 3)
Approach: This problem can be solved using C++ STL Set and recursion based on the following idea:
Try to push all the possible subsets in the set recursively following the below conditions
- either pick the element and push it to container and move to the next element
- or dont pick the element and move to the next position
Follow the steps to solve the problem:
- Create a set of vectors to store our answer.
- Sort the given array as the need is to get subsets in sorted order.
- Now recursively push all the subsets possible in the set by following the below approach for every ith element in the given array
- Pick the element and push it into the vector and move to the i + 1 position
- or don’t pick and move to the i+1 position
- After completion of the above process, the set will contain the required subsets. Now just push all the vectors in the set into another vector of vectors and return that as the result.
Below is the implementation of the above approach:
C++
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std; void solve(vector< int >& arr, int n, set<vector< int > >& ans, vector< int > v, int i) { if (i >= n) { ans.insert(v); return ; } // Not pick solve(arr, n, ans, v, i + 1); // Pick v.push_back(arr[i]); solve(arr, n, ans, v, i + 1); } vector<vector< int > > AllSubsets( vector< int > arr, int n) { // Set of vectors to store // required unique subsets set<vector< int > > ans; sort(arr.begin(), arr.end()); vector< int > v; solve(arr, n, ans, v, 0); // Vector of vectors to store final result vector<vector< int > > res; while (!ans.empty()) { res.push_back(*ans.begin()); ans.erase(ans.begin()); } return res; } // Print Function void print( int N, vector< int >& A) { vector<vector< int > > result = AllSubsets(A, N); // printing the output for ( int i = 0; i < result.size(); i++) { cout << '(' ; for ( int j = 0; j < result[i].size(); j++) { cout << result[i][j]; if (j < result[i].size() - 1) cout << " " ; } cout << "), " ; } cout << "\n" ; } // Drivers code int main() { int N = 3; vector< int > A = { 2, 1, 2 }; // Function Call print(N, A); return 0; } |
(), (1), (1 2), (1 2 2), (2), (2 2),
Time Complexity: O(2N)
Auxiliary Space: O(2N * X), where X = Length of each subset.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!