I am supposed to receive n
, and create an array of 1
to n
, then print the subsets in alphabetic order, but the goal is to create them in an alphabetic order (no array sorting) , for example for n=3
the right order would be:
{} {1} {1,2} {1,2,3} {1,3} {2} {2,3} {3}
.
so my current code finds the subsets:
for (int code = 0; code < pow(2, n); code++) {
printf("{");
counter = 0;
for (int i = 0; i < n; i++) {
if (code & (1 << i)) {
counter++;
if (counter == 1)
printf("%d", nums[i]);
else
printf(", %d", nums[i]);
}
}
puts("}");
}
The problem is printing them in the required order, and I want to write a function that would output the subsets in that order, without any sorting taking place.
The other alternative I checked was a DFS/backtracking algorithm, but even then, they won't be printed in the exact required order.
So I was wondering if DFS is the right path to go (with modifications) or if there is another algorithm which would suit me better?