1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6// Function to print the elements of a vector
7void printVector(vector<int> const &out)
8{
9 for (int i: out)
10 cout << i << " ";
11 cout << '\n';
12}
13
14// Recursive function to print all distinct subsets of S
15// S --> input set
16// out --> vector to store subset
17// i --> index of next element in set S to be processed
18void findPowerSet(int S[], vector<int> &out, int i)
19{
20 // if all elements are processed, print the current subset
21 if (i < 0)
22 {
23 printVector(out);
24 return;
25 }
26
27 // include current element in the current subset and recur
28 out.push_back(S[i]);
29 findPowerSet(S, out, i - 1);
30
31 // exclude current element in the current subset
32 out.pop_back(); // backtrack
33
34 // remove adjacent duplicate elements
35 while (S[i] == S[i-1])
36 i--;
37
38 // exclude current element in the current subset and recur
39 findPowerSet(S, out, i - 1);
40}
41
42// Program to generate all distinct subsets of given set
43int main()
44{
45 int S[] = { 1, 3, 1 };
46 int n = sizeof(S) / sizeof(S[0]);
47
48 // sort the set
49 sort(S, S + n);
50
51 // create an empty vector to store elements of a subset
52 vector<int> out;
53 findPowerSet(S, out, n-1);
54
55 return 0;
56}
57