Function to print all permutations of all subsets of an array
2 answers
Here's something for you to figure out how to do it (you need to write your code yourself, especially since I don't write C ++). The best way to do it is recursion:
getSubcombinations(Combination comb, Set set){
for a in set{
newSet=set \ {a}
getSubcombinations(comb+a, newSet)
}
print(comb);
}
The method calls itself, incrementing the current subset with the "a" element and each combination of registries (set without a), and will also return the current subset if you don't add additional elements. If your set has no duplicates (it is a set!), This will not yield duplicate combinations (that's what you are asking for, not subsets!).
+2
source to share
#include <iostream>
#include <vector>
#include <algorithm>
void subsets(int n, int r)
{
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
std::vector<int> p;
for (int i = 0; i < n; ++i)
if (v[i])
p.push_back(i);
do {
std::cout << " { ";
for(auto i : p)
std::cout << i << ' ';
std::cout << "} ";
} while(std::next_permutation(p.begin(), p.end()));
} while (std::prev_permutation(v.begin(), v.end()));
}
void subsets(int n)
{
for(int r=0; r<=n; ++r)
subsets(n, r);
}
int main()
{
subsets(4);
}
0
source to share