Algorithms · Visualized
Subsets (Backtracking)
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Generates every possible subset of a set by exploring, at each element, the two branches of a decision tree: 'include this element' and 'don't include this element'. Time: O(n × 2ⁿ) average, O(n × 2ⁿ) — 2ⁿ subsets, each up to O(n) to copy worst; space: O(n) recursion depth, O(n × 2ⁿ) total output storage.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Subsets (Backtracking)
BacktrackingGenerates every possible subset of a set by exploring, at each element, the two branches of a decision tree: 'include this element' and 'don't include this element'. Every root-to-leaf path through this tree represents one unique subset.
How Subsets (Backtracking) Works
- Start with an empty 'current path' and an index pointing at the first element.
- Record the current path as a valid subset (every point in the recursion is a valid subset, not just the leaves).
- For each element starting from the current index, add it to the path (the 'include' choice) and recurse with the next index.
- After returning from that recursive call, remove the element from the path (backtrack) to try not including it going forward.
- This explores every combination without duplicating work.
Subsets (Backtracking) Worked Example
Input: [1, 2, 3]
Record []. Include 1 → record [1]. Include 2 → record [1,2]. Include 3 → record [1,2,3]. Backtrack, backtrack. Include 3 (skip 2) → record [1,3]. Backtrack fully, try starting from 2 → record [2], [2,3]. Try starting from 3 → record [3]. Total: all 8 subsets of [1,2,3].
def subsets(a):
out = []
def build(i, cur):
if i == len(a):
out.append(cur[:])
return
build(i + 1, cur)
cur.append(a[i])
build(i + 1, cur)
cur.pop()
build(0, [])
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Subsets (Backtracking) Time & Space Complexity
When to Use Subsets (Backtracking)
- Exploring all possible selections for knapsack-style or combination problems.
- A template pattern reused across many 'choose or skip' backtracking problems.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.