What is Subset Sum
Return 1 when some subset of nums adds up to target, otherwise 0. The empty subset sums to 0, so a target of 0 is always reachable.
Example. nums = [1, 2, 3] and target = 3 returns 1. Both {3} and {1, 2} work. [1, 2, 5] with target 4 returns 0.
Input: 1 2 3, target 3 Output: 1
Constraints. 0 ≤ n ≤ 16, 0 ≤ nums[i] ≤ 1000, 0 ≤ target ≤ 20000. This picture draws the first 3 numbers.
Approach
nums[i], and also take it when it does not exceed the remainder. Either success is enough.Recursion tree
The whole tree is drawn when the page opens. Next and Play start again from the first call.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(2^n) | Each index has a skip branch and, when it fits, a take branch. |
| Stack | O(n) | The depth follows the index from 0 to n. |
Implementation
def subset(i, remain):
if remain == 0:
return 1
if i == n:
return 0
skip = subset(i + 1, remain)
take = 0
if nums[i] <= remain:
take = subset(i + 1, remain - nums[i])
return 1 if skip or take else 0