#78
Medium
Backtracking

Subsets

Return all possible subsets of the given array.

BacktrackingBit Manipulation

Pattern fit

This is the gentlest backtracking tree: each element is either taken or skipped. It can also be solved with bitmask enumeration, which makes it a great bridge problem.

Key observation

Each index creates a binary decision, so the whole answer space is a decision tree of depth n.

Target complexity

O(n * 2^n) / O(n)

How to break down the solution cleanly

1

This is the gentlest backtracking tree: each element is either taken or skipped. It can also be solved with bitmask enumeration, which makes it a great bridge problem.

2

Each index creates a binary decision, so the whole answer space is a decision tree of depth n.

3

Model the decision tree explicitly.

4

Choose the next candidate set for the current depth.

Reference implementation

Python
# Generic pattern template
def backtrack(path):
    if complete(path):
        answer.append(path[:])
        return
    for choice in choices(path):
        if not valid(choice, path):
            continue
        path.append(choice)
        backtrack(path)
        path.pop()

Common pitfalls

warning

Forgetting to copy the current path before pushing it into the answer.

warning

Mixing combination indexing and permutation-style used arrays.

Common follow-ups

How would the bitmask version look?

How do duplicates change the recursion?

Continue with related problems

Build repeatable depth inside the Backtracking cluster before moving on.

view_weekBack to the pattern page
LeetCode 78. Subsets Guide | Interview AiBox