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 −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
      cout << "[";
      for(int i = 0; i<v.size(); i++){
         cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   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()){
            res.push_back(temp);
            x.insert(temp);
         }
         return;
      }
      solve(idx+1, temp, v);
      temp.push_back(v[idx]);
      solve(idx+1, temp, v);
      temp.pop_back();
   }
   vector<vector<int> > subsetsWithDup(vector<int> &a) {
      res.clear();
      x.clear();
      sort(a.begin(), a.end());
      vector <int> temp;
      solve(0, temp, a);
      sort(res.begin(), res.end(), cmp);
      return res;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,2};
   print_vector(ob.subsetsWithDup(v));
}

Input

[1,2,2]

Output

[[],[1, ],[1, 2, ],[1, 2, 2, ],[2, ],[2, 2, ],]
raja
Published on 03-Feb-2020 14:57:22
Advertisements