Tensorum

Recursion & Backtracking

Subsets, combinations, permutations and constraint search — choose, explore, un-choose.

DSAIntermediate21 hrs8 patterns · 28 problems
0%
your progress

Core idea

Build the answer incrementally; at each step try every valid choice, recurse, then undo. Prune as early as constraints allow.

Reach for it when

  • Generate all subsets, permutations or combinations
  • Constraint satisfaction (N-Queens, Sudoku)
  • Search a grid for words or paths

Template

def subsets(nums):
    res, path = [], []
    def go(i):
        if i == len(nums):
            res.append(path[:])
            return
        path.append(nums[i]); go(i + 1); path.pop()   # take
        go(i + 1)                                      # skip
    go(0)
    return res

Complexity

Exponential by nature — O(2ⁿ) subsets, O(n!) permutations; pruning decides real cost.

Common pitfalls

  • Appending the live path instead of a copy
  • Not skipping duplicates after sorting
  • Forgetting to undo state on every exit path

Recognition cues

SubsetsCombinationsPermutationsConstraint SearchGrid Search