Dynamic Programming21 sections · 916 units
Open in Course

Subset Sum - Key Observation

Bitmask as subset

Each integer from 00 to 2n12^n - 1 represents exactly one subset. The mask tells you which elements to include. Iterate through all masks, and for each one, compute the sum of included elements. For mask =5= 5 (binary 101101) with array [3,1,4][3, 1, 4]: bits 00 and 22 are set, so include arr[0]=3arr[0] = 3 and arr[2]=4arr[2] = 4. Sum =7= 7.

This is brute-force, but 2202^{20} operations is fast enough. No clever DP (dynamic programming) needed here. The bitmask just gives you a clean way to enumerate all subsets without recursion.