Dynamic Programming21 sections · 916 units
Open in Course

SOS DP - Space Optimization

Drop the second dimension

You don't need to store all dp[mask][i]dp[\text{mask}][i] values. Process bits from 00 to n1n-1. When computing layer ii, you only need layer i1i-1. Better: update in-place.

Start with dp[mask]=f[mask]dp[\text{mask}] = f[\text{mask}]. For each bit ii from 00 to n1n-1, update: if bit ii is set in mask, add dp[mask2i]dp[\text{mask} \oplus 2^i] to dp[mask]dp[\text{mask}]. The order matters: process masks with bit ii set after masks without it, or iterate masks in increasing order. This keeps dp[mask2i]dp[\text{mask} \oplus 2^i] at its layer i1i-1 value when you read it.