Subset Iteration with Bitmasks

Iterating over subsets of a subset.

Iterate all subsets of a mask:

sub = mask
while sub > 0:
    // process subset 'sub'
    sub = (sub - 1) & mask
// don't forget empty subset

Why it works: Decrementing flips trailing 11s and sets next 00 to 11. The & mask keeps only bits from the original mask.

Example: mask =1011= 1011, subsets: 1011,1010,1001,1000,0011,0010,0001,00001011, 1010, 1001, 1000, 0011, 0010, 0001, 0000.

Time: O(3n)O(3^n) for iterating all subsets of all masks from 00 to 2n12^n - 1.