Subsets II in C++

C++Server Side ProgrammingProgramming

Suppose we have a set of numbers; we have to generate all possible subsets of that set. This is also known as power set. We have to keep in mind that the elements may be duplicate. So if the set is like [1,2,2], then the power set will be [[], [1], [2], [1,2], [2,2], [1,2,2]]

Let us see the steps −

  • Define one array res and another set called x

  • We will solve this using recursive approach. So if the recursive method name is called solve(), and this takes index, one temporary array, and the array of numbers (nums)

  • The solve() function will work like below −

  • if index = size of v, then

    • if temp is not present in x, then insert temp into res and also insert temp into x

    • return

  • call solve(index + 1, temp, v)

  • insert v[index] into temp

  • call solve(index + 1, temp, v)

  • remove last element from temp

  • The main function will be like below −

  • clear the res and x, and sort the given array, define an array temp

  • call solve(0, temp, array)

  • sort the res array and return res


Let us see the following implementation to get better understanding −

class Solution {
   vector < vector <int> > res;
   set < vector <int> > x;
   static bool cmp(vector <int> a, vector <int> b){
      return a < b;
   void solve(int idx, vector <int> temp, vector <int> &v){
      if(idx == v.size()){
         if(x.find(temp) == x.end()){
      solve(idx+1, temp, v);
      solve(idx+1, temp, v);
   vector<vector<int> > subsetsWithDup(vector<int> &a) {
      sort(a.begin(), a.end());
      vector <int> temp;
      solve(0, temp, a);
      sort(res.begin(), res.end(), cmp);
      return res;




Published on 03-Feb-2020 10:27:22