Workspace Recursion And Backtracking
0d
DSA Cheat Sheets

Recursive frames

Each descent owns its arguments. Each return supplies the missing operand in its caller. For the fixed-width snippets use 0 ≤ n ≤ 20.

Base caseKnown direct answer0! = 1
Progress measureStrictly decreasesn becomes n − 1
Auxiliary spaceMaximum live framesFactorial uses O(n) call stack
BacktrackingUndo shared mutationRestore the path before its sibling branch

Python

def factorial(n):
    if n == 0: return 1
    return n * factorial(n-1)

C++

long long factorial(int n) {
  if (n == 0) return 1;
  return n * factorial(n-1);
}

Java

static long factorial(int n) {
  if (n == 0) return 1L;
  return n * factorial(n-1);
}