CS concepts

Backtracking Explained: Subsets, Permutations and Combinations

Updated Nov 28, 2026 · 4 min read

Backtracking explores a decision tree with recursion: choose an option by adding it to the path, explore by recursing for the next choice, then un-choose by popping it off so the next branch starts clean. Subsets, permutations and combination sum all use this one template; only what counts as complete and which choices come next change.

Backtracking reel cover

Key points

  • ●The template is three moves: choose, explore, un-choose.
  • ●Save a copy of the path (path[:]), or every answer comes out empty.
  • ●Subsets: record every path, recurse with i + 1. Permutations: record when full, skip used.
  • ●Combination sum: recurse with i to allow reuse, sort and break when you overshoot.
  • ●n up to about 10 to 20 in the constraints is the hint to try everything.
Step-by-step visual sheet: Backtracking
The full visual sheet, made with Edithly.Open the interactive sheet

Three questions, one template

The numbers 1, 2 and 3 have 8 subsets and 6 different orders. From 2, 3, 6 and 7, exactly 2 combinations add up to 7. Three different questions, and all three are solved by the same few lines of recursion. That's backtracking.

Think of walking a maze. You pick a path. If it dead-ends, you step back to the last fork and try the next way. You never start over from the entrance. In code, the maze is a decision tree: every level is one choice, every leaf is one finished answer, and recursion does the stepping back for you. Whenever a question says "all" or "every", think backtracking.

The template: choose, explore, un-choose

def backtrack(path):
    if is_complete(path):
        result.append(path[:])
        return
    for choice in choices(path):
        path.append(choice)    # choose
        backtrack(path)        # explore
        path.pop()             # un-choose

The pop is the "back" in backtracking. You reuse one list the whole time, and popping returns it to exactly how it was before the branch. Each problem below changes only two things: what counts as complete, and which choices are allowed next.

Subsets (LeetCode 78): take or skip

Every number gets a yes or a no. Three numbers with two choices each is 2 x 2 x 2 = 8 subsets.

def subsets(nums):
    result = []
    def backtrack(start, path):
        result.append(path[:])   # a copy, not path
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()
    backtrack(0, [])
    return result

Every path is an answer here, so you record at the top of every call, not only at the leaves. The start index means you only look forward, so you get [1, 2] but never [2, 1]. On [1, 2, 3] the order of records is [], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]. The visual sheet above walks the same tree step by step.

The bug that empties every answer. Write result.append(path) without the [:] and every answer comes out empty. You saved 8 references to the same list, and by the end it has been popped back to nothing. Always save a copy.

Permutations (LeetCode 46): fill every slot

Now order matters. The first slot can be any of 3 numbers, the second any of the 2 left, the last the 1 remaining: 3 x 2 x 1 = 6.

def permute(nums):
    result = []
    def backtrack(path, used):
        if len(path) == len(nums):
            result.append(path[:])
            return
        for x in nums:
            if x in used:
                continue
            used.add(x)
            path.append(x)
            backtrack(path, used)
            path.pop()
            used.remove(x)
    backtrack([], set())
    return result

Two changes from subsets: record only when the path is full, and loop over every number while skipping used ones. Notice you un-choose twice, popping the path and removing from used. Forget the second and the tree stops after one branch.

Combination Sum (LeetCode 39): reuse, no repeated orders

From [2, 3, 6, 7], find every combination that adds up to 7, reusing numbers as often as you like. [2, 2, 3] and [3, 2, 2] are the same answer.

def combination_sum(candidates, target):
    result = []
    candidates.sort()
    def backtrack(start, path, left):
        if left == 0:
            result.append(path[:])
            return
        for i in range(start, len(candidates)):
            if candidates[i] > left:
                break
            path.append(candidates[i])
            backtrack(i, path, left - candidates[i])
            path.pop()
    backtrack(0, [], target)
    return result

One change does both jobs: recurse with i, not i + 1. Passing i lets you pick the same number again, and never going below i stops repeated orders. The trace: 2, 2, 2 leaves 1, a dead end. 2, 2, 3 hits 0, record it. Later 7 alone hits 0, record it. The result is [[2, 2, 3], [7]].

Pruning and duplicates

That break is pruning. Because the candidates are sorted, once one is bigger than what's left, every later one is too, so you stop the whole loop. Pruning doesn't change the worst case, but it changes how much of the tree you actually walk.

If the input has repeats, like [1, 2, 2], plain subsets returns [1, 2] twice. Sort first, then skip a number that equals the one just before it at the same level:

if i > start and nums[i] == nums[i - 1]:
    continue

The same idea works on a grid. In Word Search (LeetCode 79) you choose a cell by marking it visited, explore its four neighbours, and un-choose by unmarking it on the way back.

How big is too big

Backtracking lists every answer, so it's only as fast as the number of answers. Subsets are 2^n: 20 items is about a million, fine, while 30 is a billion. Permutations are n!: 10 items is 3.6 million. The recursion depth is only n, so the problem is the width of the tree, not the depth. When the constraints say n is at most about 10 to 20, that's the hint they expect you to try everything. Give the complexity as the number of answers times n for copying each one: subsets are O(n x 2^n).

Frequently asked questions

What is the difference between backtracking and recursion?

Recursion is the tool; backtracking is a way of using it. Backtracking is recursion over a decision tree where you undo each choice after exploring it, so one shared path list is reused for every branch.

Why does my backtracking return empty lists?

You appended the path itself instead of a copy. Every saved answer points to the same list, and by the end it has been popped back to empty. Use result.append(path[:]).

What is the time complexity of backtracking?

It depends on how many answers there are, times n for copying each one. Subsets are O(n x 2^n) and permutations are O(n x n!). Pruning cuts how much of the tree you walk but doesn't change the worst case.

How do you handle duplicates in backtracking?

Sort the input, then at each level skip a number equal to the one just before it: if i > start and nums[i] == nums[i - 1], continue. That's the fix in LeetCode 90 and 47.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free