SDE & MLE Prep

Backtracking

When to use: "generate all …" (subsets, permutations, combinations, partitions, boards). Explore a decision tree depth-first: choose → recurse → un-choose.

def backtrack(start, path):
    if is_solution(path):
        res.append(path[:])           # copy!
        return                         # (subsets: record at every node, no return)
    for i in range(start, len(choices)):
        if i > start and choices[i] == choices[i - 1]:
            continue                   # skip duplicates (sorted input)
        path.append(choices[i])
        backtrack(i + 1, path)         # i  -> reuse allowed;  i+1 -> each used once
        path.pop()
subsets of [1,2,3]               []
                       /          |        \
                    [1]          [2]       [3]
                   /   \          |
               [1,2]  [1,3]     [2,3]
                 |
              [1,2,3]
Problem typestart indexdedupeused[]
Subsets / combinationsi + 1sort + skip i > start dup–
Combination sum (reuse)i––
Permutations0sort + skip if prev dup unusedyes

Problems