Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Given a set, find XOR of the XOR's of all subsets.
Next article icon

Find all unique subsets of a given set using C++ STL

Last Updated : 26 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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;
}
 
 
Output
(), (1), (1 2), (1 2 2), (2), (2 2), 

Time Complexity: O(2N)
Auxiliary Space:  O(2N * X), where X = Length of each subset.



Next Article
Given a set, find XOR of the XOR's of all subsets.
author
ishankhandelwals
Improve
Article Tags :
  • Arrays
  • Combinatorial
  • DSA
  • cpp-set
  • STL
  • subset
Practice Tags :
  • Arrays
  • Combinatorial
  • STL
  • subset

Similar Reads

  • Find all Unique Subsets of a given Set
    Given an array A[] of positive integers, print all the unique non-empty subsets of the array  Note: The set can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples:  Input: A[] = {1, 5, 6}Output: {{1}, {1, 5}, {1, 6}, {5}, {5, 6}, {6}, {1, 5,
    15+ min read
  • Given a set, find XOR of the XOR's of all subsets.
    The question is to find XOR of the XOR's of all subsets. i.e if the set is {1,2,3}. All subsets are : [{1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]. Find the XOR of each of the subset and then find the XOR of every subset result.We strongly recommend you to minimize your browser and try this yo
    5 min read
  • Find all distinct subsets of a given set using BitMasking Approach
    Given an array of integers arr[], The task is to find all its subsets. The subset can not contain duplicate elements, so any repeated subset should be considered only once in the output. Examples: Input: S = {1, 2, 2}Output: {}, {1}, {2}, {1, 2}, {2, 2}, {1, 2, 2}Explanation: The total subsets of gi
    12 min read
  • Finding all subsets of a given set in Java
    Problem: Find all the subsets of a given set. Input: S = {a, b, c, d} Output: {}, {a} , {b}, {c}, {d}, {a,b}, {a,c}, {a,d}, {b,c}, {b,d}, {c,d}, {a,b,c}, {a,b,d}, {a,c,d}, {b,c,d}, {a,b,c,d} The total number of subsets of any given set is equal to 2^ (no. of elements in the set). If we carefully not
    2 min read
  • Print sums of all subsets of a given set
    Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order. Examples : Input: arr[] = {2, 3}Output: 0 2 3 5Explanation: All subsets of this array are - {{}, {2}, {3}, {2, 3}}, having sums - 0, 2, 3 and 5 respectively.Input: arr[] = {2, 4, 5}Output: 0 2 4 5 6
    10 min read
  • Find the maximum subset XOR of a given set
    Given a set of positive integers. find the maximum XOR subset value in the given set. Expected time complexity O(n). Examples: Input: set[] = {2, 4, 5}Output: 7The subset {2, 5} has maximum XOR valueInput: set[] = {9, 8, 5}Output: 13The subset {8, 5} has maximum XOR valueInput: set[] = {8, 1, 2, 12,
    15+ min read
  • Sum of all subsets of a given size (=K)
    Given an array arr[] consisting of N integers and a positive integer K, the task is to find the sum of all the subsets of size K. Examples: Input: arr[] = {1, 2, 4, 5}, K = 2Output: 36Explanation:The subsets of size K(= 2) are = {1, 2}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {4, 5}. Now, the sum of all sub
    7 min read
  • Print all subsets of given size of a set
    Generate all possible subsets of size r of the given array with distinct elements. Examples: Input : arr[] = {1, 2, 3, 4} r = 2Output : 1 2 1 3 1 4 2 3 2 4 3 4Input : arr[] = {10, 20, 30, 40, 50} r = 3Output : 10 20 30 10 20 40 10 20 50 10 30 40 10 30 50 10 40 50 20 30 40 20 30 50 20 40 50 30 40 50
    15+ min read
  • Find the subset of Array with given LCM
    Given an array arr[] consisting of N positive integers and a positive integer X, the task is to find the subset of the given array whose Lowest Common Multiple(LCM) is X. If there doesn't exists any subset then print "-1". Examples: Input: arr[ ] = {2, 4, 3, 5}, X = 20Output: {4, 5}Explanation:Consi
    8 min read
  • Number of subsets with a given AND value
    Given an array arr of length N and an integer X, the task is to find the number of subsets whose AND value is X.Examples: Input: arr[] = {2, 3, 2} X = 2 Output: 6 All possible subsets and there AND values are: {2} = 2 {3} = 3 {2} = 2 {2, 3} = 2 & 3 = 2 {3, 2} = 3 & 2 = 2 {2, 2} = 2 & 2 =
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences