Hey everyone!
I have an interesting question about the power set solution:
Implement a method that takes an inputs as input a set S of n distinct elements, and prints the power set of S. Print the subsets one per line, with elements separated by commas.
In the recursion approach, we print out the subset if it’s not empty:
void generate_power_set_helper(const vector<int>& S,
int m, vector<int>* subset)
{
if (!subset->empty()) {
// Print the subset here.
}
...
}
Because generate_power_set_helper
will be called multiple times due to the exponential run time, to avoid heavy I/O I think a better way is use a container to store the all subsets and after recursion step print all the result (implement in Java):
void generatePowerSet(List<Integer> S) {
if (S == null) {
return;
}
List<List<Integer>> subsets = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<>();
generatePowerSetHelper(S, 0, path, subsets);
for (List<Integer> path : subsets) {
// Print it here
}
}
I checked our Java version PowerSetAlternative.java, but still think it’s worth to discuss iff we want to print the result instead returning it.