awelgorithms

Bitmask DP on subsets

Updated

State is a subset packed in bits: bit i means a[i] is in the subset. dp[mask] answers that subset. Transition: try the next element not in the mask, go to mask|(1<<i). 2^n states.

What to focus on

n=3 on a = [1, 4, 9] has 8 masks. mask 0 is the empty subset of a non-empty array. Iterate by increasing popcount or rec with a cache on the mask.

Worked examples

sum of a subset

a = [1, 4, 9], mask = 0b011
  1. bits 0 and 1
  2. 1+4=5

Result: dp[3]=5

empty mask

a = [1, 4, 9], mask = 0
  1. no bits
  2. sum 0

Result: 0

full mask

a = [1, 4, 9], mask = 0b111
  1. 1+4+9=14

Result: 14

Try it

Write maskSum(a, mask). a contains distinct positive integers. mask is an integer in 0..2^n-1. dp[mask] is the subset sum of the bits set in mask. Name which indices sit in each mask. Return dp[mask]. mask 0b011 → 5. mask 0 → 0. mask 0b111 → 14.

a contains distinct positive integers. n = 3. mask is an integer in 0..2^n-1.