Generating Subsets by Inclusion Choices
For each distinct item, a recursive generator can branch into including it and leaving it out. The base case records the completed choices.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Check a small universe
For items A and B, the leaves yield the empty subset, A, B, and A with B. One decision per item gives \(2^n\) leaves on \(n\) distinct items. Use counting recursive calls to distinguish total visits from the number of returned items.
Decide how duplicates enter
Two equal input values at distinct positions produce multiple selection paths with equal value sets. If the result should contain unique subsets by value, apply a clear equality rule first. See membership and duplicates.[1]
Assign one independent include or exclude choice per value
With three distinct values A, B and C, every root-to-leaf path encodes one subset. The empty subset follows three excludes. Exactly one path includes A and C while excluding B. Preserving choice order avoids generating different permutations of that same subset. See set membership.
Choice bits are ordered A, B, C
000 → empty
001 → {C}
101 → {A,C}
111 → {A,B,C}
8 leaves in total
Separate output count from cost of storing each output
There are \(2^n\) subsets of \(n\) distinct items. Materializing every result as a list copies \(n2^{n-1}\) element occurrences for \(n\ge1\). If input items repeat, decide whether their positions distinguish choices or whether duplicate value sets collapse.