📐Subset Sum
Question
Examples
I: nums = [1, 2, 3, 4, 5, 6], target = 8
O: 4 (because [1, 2, 5], [1, 3, 4], [2, 6], [3, 5])
I: nums = [1, 2, 3, 4, 5, 6], target = 22
O: 0
I: nums = [7, 8, 10, 3, 5], target = 20
O: 2Analysis
DP
1. Define by prefix
dp[i][s] = number of subsets that sum to value s using prefix i elements nums[0:i]
(similar to the subset recursive search definition)
2. Solve be prefix
for the current ith element
dp[i][s] = AND(dp[i-1][s], dp[i-1][s-nums[i]])
(not use the current element, use the current element)
3. Base cases
dp[0][0] = 1 (empty subset sums to 0)
4. Topo order
for s from 0 to target
5. Final answer
dp[n][target]Code
Time Complexity
State Graph

Space Optimization
Optimized Code
Time Complexity
More Space Optimization
Optimized Complexity
Last updated