Math Fundamentals18 sections · 814 units
Open in Course

Iterating Through Subsets

Generate all subsets

To generate all subsets of nn elements, loop through all integers from 00 to 2n12^n - 1. For each integer maskmask, check which bits are set to determine which elements are in that subset.

For n=3n=3 elements {0,1,2}\{0, 1, 2\}, loop through masks 00 to 77: 000,001,010,011,100,101,110,111000, 001, 010, 011, 100, 101, 110, 111. Each mask corresponds to one subset.

To extract which elements are in subset represented by mask mm, loop through bits ii from 00 to n1n-1 and check if bit ii is set: (m&(1<<i))0(m \& (1 << i)) \neq 0.