Practice Discrete Math

Algorithms / State Compression Dp

Least You Need to Know: State-Compression DP, Bitmasks, and Small-Set Subproblems

State-compression DP works when the hard part of the problem is which small subset has already been used. Bitmasks make subset state compact, and the art is choosing what extra coordinate—such as current endpoint or last chosen item—must accompany the mask.

The least you need to know

Key notation

mask bitset describing a chosen subset
(mask, last) subset plus current endpoint or last item
sub = (sub-1) & mask iterate through submasks of `mask`

Tiny worked example

  • In a traveling-salesperson-style DP, `dp[mask][last]` stores the best cost to visit exactly the cities in `mask` and end at `last`.
  • A transition adds one new city to the mask.
  • The subset is small, but the bitmask lets you store and update all visited sets compactly.

Common mistakes

How to recognize this kind of problem

Start practice