-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistinctSubsetsOfASet.cpp
More file actions
68 lines (61 loc) · 1.11 KB
/
DistinctSubsetsOfASet.cpp
File metadata and controls
68 lines (61 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>
#include <unordered_set>
#include <vector>
#include <algorithm>
/* Distinct subsets of a set. For example:
* For the array : [1 3 1] the distinct subsets are
* {}
* {1}
* {3}
* {1, 3}
* {1, 1}
* {1, 3, 1}
*/
class SubsetComputer
{
private:
std::vector<int> arr;
std::unordered_set<std::string> subs; // to only store unique entries
public:
SubsetComputer(const std::vector<int>& a)
: arr(a)
{
// To club duplicates together.
std::sort(arr.begin(), arr.end());
}
void find()
{
std::string temp;
compute(0, temp);
std::cout << "The subsets are" << std::endl;
for (auto iter : subs)
{
if (iter.empty())
{
std::cout << "{empty}" << std::endl;
} else {
std::cout << "{" << iter << "}" << std::endl;
}
}
}
private:
void compute(int start, std::string temp)
{
subs.insert(temp);
if (start == arr.size())
{
return;
}
for (int i = start; i < arr.size(); ++i) {
compute(i + 1, temp + std::to_string(arr[i]));
}
}
};
int main()
{
std::vector<int> arr{ 1, 3, 1 };
SubsetComputer obj(arr);
obj.find();
return 0;
}