Dynamic Programming21 sections · 916 units
Open in Course

SOS DP - The Core Idea

Build subsets bit by bit

Instead of iterating subsets directly, build them incrementally. Process one bit position at a time. For each bit, either keep it or turn it off (if it was on).

Define dp[mask][i]dp[\text{mask}][i] = sum of f[submask]f[\text{submask}] where submask matches mask in bits i+1i+1 through n1n-1, and can differ in bits 00 through ii. Base case: dp[mask][1]=f[mask]dp[\text{mask}][-1] = f[\text{mask}]. No bits are flexible yet, so the only "submask" is mask itself. Final answer: dp[mask][n1]dp[\text{mask}][n-1] gives the sum over all submasks.