0PricingLogin
Competitive Programming Academy · Lesson

Bitmask Subset Enumeration

Iterate all subsets via integers.

Subsets as Numbers

Every subset of n items maps to a single integer. Count from 0 up, and each number's bits pick exactly which items are in. 🙂

How Many Subsets

A set of n items has 2^n subsets. So looping an integer from 0 to 2^n minus 1 visits every subset exactly once.

for mask in range(1 << n):
    pass  # mask is one subset

All lessons in this course

  1. Brute Force Is a Valid Strategy
  2. Enumerate with itertools
  3. Bitmask Subset Enumeration
  4. Trim the Search Space Smartly
← Back to Competitive Programming Academy