1#include <vector>
2#include <iostream>
3#include <cmath>
4using namespace std;
5
6int main() {
7 // this is the length of the array of values
8 // change variable "len" accordingly
9 int len = 5;
10 // this is the array of values
11 int values[] = {3, 4, 2, 8, 5};
12
13 // all subsets will be in vector "subsets"
14 vector<vector<int>> subsets;
15 for (int i = 0; i < pow(2, len); i++) {
16 int t = i;
17 vector<int> v;
18 for (int j = 0; j < len; j++) {
19 if (t & 1)
20 v.push_back(values[j]);
21 t >>= 1;
22 }
23 subsets.push_back(v);
24 }
25
26 // print all of the subsets (optional)
27 cout << "subsets:\n";
28 for (const vector<int>& subset: subsets) {
29 for (const int& value: subset)
30 cout << value << " ";
31 cout << "\n";
32 }
33 // note: an empty line will be printed at the top,
34 // indicating an empty subset
35}
36
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