Backtracking Template: Subsets, Combination Sum and Permutations

One backtracking template (choose, explore, un-choose) that solves Subsets, Subsets II, Combination Sum I and II and Permutations on LeetCode, with tested Python code and a free video walkthrough from an SDE Skills session.
Practice with other engineers, free. SDE Skills is a volunteer-run 501(c)(3) nonprofit with free daily LeetCode practice and weekly system design and DSA sessions on Zoom.

Watch the 2-minute explanation from a free SDE Skills session:

Backtracking is depth-first search over your choices. At each step you choose an option, explore everything that follows from it, then un-choose it and try the next option. One small template covers a whole family of LeetCode problems: subsets, combinations, permutations and their “with duplicates” versions.

When to think of it: the problem says “return all subsets / combinations / permutations / partitions”, or “find every way to …”, and the input is small (n up to about 20).

The idea: walk a tree of decisions

Draw the choices as a tree. The root is the empty list. Each edge adds one more number. Every path from the root is a partial answer, and backtracking is just a depth-first walk of that tree: go down as far as you can, then step back up and take the next branch. (session clip at 12:09)

Backtracking is a variation of DFS: you go deep into the decision tree, and when a decision stops making sense you undo it and try something else. Under the hood it is plain recursion. (session clip at 5:05)

The template: Subsets (LeetCode 78)

def subsets(nums):
    res, cur = [], []
    def backtrack(start):
        res.append(cur[:])                 # every path is a subset
        for i in range(start, len(nums)):
            cur.append(nums[i])            # choose
            backtrack(i + 1)               # explore
            cur.pop()                      # un-choose
    backtrack(0)
    return res

Three parts to remember:

  1. Record: decide when the current path is an answer. For subsets, every path is one, so record first.
  2. Loop over choices from start: starting at start (not 0) is what stops [1, 2] and [2, 1] from both appearing.
  3. Choose, recurse, un-choose: the pop() is the “backtrack”. Without it, cur keeps growing.

(session clip at 30:42)

Time is O(n · 2ⁿ): there are 2ⁿ subsets and copying each one costs up to n.

Example 2: Subsets II, with duplicates (LeetCode 90)

With [1, 2, 2] the template above returns [1, 2] twice. The fix discussed in the session: sort first, then skip a number if it equals the one before it at the same depth. (session clip at 49:20)

def subsets_with_dup(nums):
    nums = sorted(nums)
    res, cur = [], []
    def backtrack(start):
        res.append(cur[:])
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue                   # same value at the same depth: skip
            cur.append(nums[i])
            backtrack(i + 1)
            cur.pop()
    backtrack(0)
    return res

The check is i > start, not i > 0: picking the second 2 right after the first one (a deeper level) is still allowed, which is how [2, 2] gets in.

Example 3: Combination Sum (LeetCode 39)

Now only paths that add up to target count, and the same number may be reused. Two changes to the template: record only when remaining == 0, and recurse with i instead of i + 1 so the same number can be picked again. (session clip at 1:12:12)

def combination_sum(candidates, target):
    candidates = sorted(candidates)
    res, cur = [], []
    def backtrack(start, remaining):
        if remaining == 0:
            res.append(cur[:])
            return
        for i in range(start, len(candidates)):
            if candidates[i] > remaining:
                break                      # sorted, so every later number is too big: prune
            cur.append(candidates[i])
            backtrack(i, remaining - candidates[i])   # i, not i + 1: reuse allowed
            cur.pop()
    backtrack(0, target)
    return res

The break is pruning: once a number is too big, every number after it in sorted order is too big as well, so the whole branch is cut. That is what keeps backtracking fast in practice. (session clip at 1:44:09)

Example 4: Combination Sum II (LeetCode 40)

Each number may be used once and the input has duplicates. Combine the two ideas above: skip equal neighbours at the same depth, and recurse with i + 1.

def combination_sum2(candidates, target):
    candidates = sorted(candidates)
    res, cur = [], []
    def backtrack(start, remaining):
        if remaining == 0:
            res.append(cur[:])
            return
        for i in range(start, len(candidates)):
            if i > start and candidates[i] == candidates[i - 1]:
                continue
            if candidates[i] > remaining:
                break
            cur.append(candidates[i])
            backtrack(i + 1, remaining - candidates[i])   # each number once
            cur.pop()
    backtrack(0, target)
    return res

Example 5: Permutations (LeetCode 46)

Order matters now, so the loop starts at 0 every time and a used array stops a number from appearing twice in the same permutation. Record only when the path is full length.

def permute(nums):
    res, cur, used = [], [], [False] * len(nums)
    def backtrack():
        if len(cur) == len(nums):
            res.append(cur[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            used[i] = True
            cur.append(nums[i])
            backtrack()
            cur.pop()
            used[i] = False
    backtrack()
    return res

Cheat sheet: what changes between problems

Problem Record when Loop starts at Recurse with Extra
Subsets (78) every call start i + 1  
Subsets II (90) every call start i + 1 sort, skip i > start duplicates
Combination Sum (39) remaining == 0 start i sort, break when too big
Combination Sum II (40) remaining == 0 start i + 1 sort, skip duplicates, break
Permutations (46) len(cur) == n 0 (no index) used array

Common mistakes

  • Appending cur instead of cur[:]. Every saved answer then points at the same list, which ends up empty.
  • Forgetting the pop(). The path keeps growing and answers bleed into each other.
  • Skipping duplicates with i > 0. That also blocks valid answers like [2, 2]; use i > start.
  • Looping from 0 for combinations. You get [1, 2] and [2, 1]; only permutations loop from 0.

Practice problems

Problem Twist
Subsets (78) The base template
Subsets II (90) Duplicates in the input
Combinations (77) Record when the path has k items
Combination Sum (39) Reuse allowed, prune by sum
Combination Sum II (40) Use once, duplicates
Combination Sum III (216) Fixed size k and a sum
Permutations (46) used array, loop from 0
Permutations II (47) Sort and skip used duplicates
Letter Combinations of a Phone Number (17) Choices come from a map
Palindrome Partitioning (131) Choose where to cut
Word Search (79) Backtracking on a grid
N-Queens (51) Prune with column and diagonal sets

For graph-style backtracking (grids, mazes), see the graph algorithms guide. Many of these problems are also on the free DSA practice sheet.

Video walkthrough

Backtracking template, subsets with duplicates and combination sum I and II (SDE Skills weekly algorithms session)

Practice with others, free

SDE Skills is a volunteer-run 501(c)(3) nonprofit with free daily LeetCode practice on Zoom. See the schedule and the free DSA practice sheet.

Join a session on Zoom Join our free Discord