#78

Subsets

Medium Backtracking (pick / not pick)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return every possible subset of an array of distinct integers.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: list every subset.

Why this works: each node of the recursion is a subset. From a start index, try adding each later element, recurse, then remove it.

Example: [1, 2, 3]

[] → [1] → [1,2] → [1,2,3]back → [1,3]back → [2] → [2,3] → [3]8 subsets

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Adding the path itself instead of new ArrayList<>(path) — every stored subset ends up as the same empty list.

Solve on LeetCode ↗
Complexity
  • Time: O(n · 2^n).
  • Space: O(n) recursion besides the output.
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon