Subset Sum
Question
Given a list of positive integers, return the number of subsets that sum to the target value.
Examples
Analysis
The brute force solution is just generating all subsets recursively then checking the sum and updating a count. The key observation is that some subproblems overlap. For example, search_subset(target=5)
can overlap search_subset(target=4)
with and search_subset(target=2)
. We can give DP a shot.
DP
Code
Time Complexity
time O(n * target) space O(n * target)
State Graph
Space Optimization
The value keys can be sparse. For example, for nums = [1, 100, 1001, 2002], target = 3003
, we don't have to store all the values between 1
to 3003
. We only have to store the valid subset sum values in the memoization table. To optimize the data structure for memoization, we can use a nested dictionary rather than a 2D array.
Optimized Code
Time Complexity
min_target = min(2^n, target)
time O(n * min_target) space O(n * min_target)
More Space Optimization
We only have optimized space from the target value dimension so far. We can also optimize the ith element index dimension.
We can see from the recursive step
only depends on the previous index of the state.
We can mod the ith dimension to only store 2 layers of state at a time.
Optimized Complexity
time O(n * min_target) space O(min_target)
Last updated