Part 17 / Topic 10 of 20
Recursion, divide and conquer, and backtracking
Recursion is a function calling a smaller copy of itself until it reaches a base case it can answer directly. Backtracking is recursion with a specific shape: try a choice, recurse into what happens next, then undo the choice before trying the next option - so every possibility gets explored and abandoned branches cost nothing once undone. A related shape, divide and conquer, splits the input in half, solves each half, and combines the results — binary search and merge sort are the famous ones; you will rarely hand-write others. Think of nesting dolls for recursion (each doll holds a smaller copy of the same shape) and a maze runner for backtracking: try a turn, if it's a dead end walk back to the junction (undo) and try the next turn.
def factorial(n): # base case: 0! = 1
if n == 0:
return 1
return n * factorial(n - 1) # smaller copy of the same problem
print(factorial(5)) # 120
Naive recursion can repeat the same work many times. Fibonacci without memory of past answers makes roughly double the calls for every +1 in n - O(2ⁿ):
def fib_naive(n):
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
# fib_naive(5) -> 15 calls
# fib_naive(10) -> 177 calls
# fib_naive(20) -> 21,891 calls
The dynamic programming topic later in this part fixes exactly this blow-up.
Backtracking, generating every order to visit a small set of delivery stops:
def delivery_stop_orders(stops):
results, path, used = [], [], set()
def backtrack():
if len(path) == len(stops):
results.append(path.copy())
return
for stop in stops:
if stop in used:
continue
path.append(stop); used.add(stop) # choose
backtrack() # explore
path.pop(); used.discard(stop) # un-choose (backtrack)
backtrack()
return results
print(len(delivery_stop_orders(["Kothrud", "Baner", "Hinjewadi"]))) # 6
Six stops give 3×2×1 = 6 possible orders - this is exactly the pattern behind "try every arrangement" problems.
Real-world example: a 3-stop delivery round trip has 6 possible visiting orders; a route-planning tool that needs to compare all of them (before the graphs topic later in this part picks the best one by distance) generates them with exactly this backtracking shape.
⚠️ Every recursive function needs a base case that is reachable - forgetting one gives infinite recursion until Python raises
RecursionError(about 1,000 nested calls by default —sys.getrecursionlimit()— so deep inputs need an iterative rewrite or an explicit stack). Backtracking without "undoing" the choice (for example, forgettingpath.pop()) leaves later branches polluted with earlier choices.
Practice: generate all permutations, combinations or subsets of a small set; maze or grid path-finding with backtracking; constraint placement (seating arrangements, N-queens-style puzzles).
Practice on LeetCode - start here: Subsets · Permutations · Letter Combinations of a Phone Number · Combination Sum · Word Search
Show the full practice list (15 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Combinations | Medium |
| Subsets II | Medium |
| Permutations II | Medium |
| Combination Sum II | Medium |
| Combination Sum III | Medium |
| Letter Case Permutation | Medium |
| Restore IP Addresses | Medium |
| Gray Code | Medium |
| Beautiful Arrangement | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Palindrome Partitioning | Medium |
| Partition to K Equal Sum Subsets | Medium |
| Matchsticks to Square | Medium |
| N-Queens | Hard |
| N-Queens II | Hard |
| Sudoku Solver | Hard |
Full program: examples/10_recursion_backtracking.py.
Exercise 10: Recursion/backtracking — every way to split a tip
Scenario: Three friends want every possible way to pay a ₹300 bill using only ₹100 and ₹50 notes each person can either contribute or not — just the patterns, not who pays what.
What to do: Write note_combinations(notes: list[int], target: int) -> list[list[int]], returning every subset of notes (backtracking, like parcel_subsets in examples/10_recursion_backtracking.py) whose sum equals target. Notes are picked by POSITION, so two notes with the same value (there are three ₹100 notes here) still count as different choices. Sort each combination, then sort the list of combinations, so the output is predictable. Print every matching combination for the data below.
Starting data:
NOTES = [100, 100, 50, 50, 100]
TARGET = 300
Sample output:
Notes: [100, 100, 50, 50, 100]
Combinations summing to 300: 4
[50, 50, 100, 100]
[50, 50, 100, 100]
[50, 50, 100, 100]
[100, 100, 100]
Show the solution to Exercise 10
"""Exercise 10: Recursion/backtracking - every way to split a tip.
Run: python ex05.py (macOS/Linux: python3 ex05.py)
"""
NOTES = [100, 100, 50, 50, 100]
TARGET = 300
def note_combinations(notes: list[int], target: int) -> list[list[int]]:
"""Every subset of `notes` (by position, so repeated values count
separately) that sums to `target`. Backtracking: try each position
without it, then with it, undoing the choice afterwards."""
results: list[list[int]] = []
current: list[int] = []
def backtrack(index: int) -> None:
if index == len(notes):
if sum(current) == target:
results.append(current.copy())
return
backtrack(index + 1) # without notes[index]
current.append(notes[index])
backtrack(index + 1) # with notes[index]
current.pop()
backtrack(0)
return sorted(sorted(combo) for combo in results)
def main() -> None:
combos = note_combinations(NOTES, TARGET)
print(f"Notes: {NOTES}")
print(f"Combinations summing to {TARGET}: {len(combos)}")
for combo in combos:
print(f" {combo}")
if __name__ == "__main__":
main()