Recursion · Take or skip · Decision tree

Subset Sum Visualizer

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

Base case A remaining target of 0 means the chosen numbers already add up. Return 1. Running out of numbers with a positive remainder returns 0.
Recursive case Skip nums[i], and also take it when it does not exceed the remainder. Either success is enough.

Recursion tree

Interactive recursion tree
Step 0/0 Answer —

The whole tree is drawn when the page opens. Next and Play start again from the first call.

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

Complexity

PieceCostWhy
TimeO(2^n)Each index has a skip branch and, when it fits, a take branch.
StackO(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