Math Fundamentals18 sections · 814 units
Open in Course

Subsets - Bitmask Approach

Using bit manipulation

The idea: with nn elements, there are 2n2^n subsets. Loop through all integers from 00 to 2n12^n - 1, treating each as a bitmask.

For each mask, build a subset by including element ii if bit ii is set. For [1,2,3][1,2,3] and mask 5=1015 = 101, bits 0 and 2 are set, so the subset is [1,3][1, 3].

This works because it directly maps the binary representation of numbers to subsets. No recursion needed.