跳到主要内容

考前速记

Recursion Template

def func(parameters):
if base_condition:
return base_value
else:
return combine(parameters, func(smaller_parameters))

Key Rules

RuleWhy
Must have base caseStops infinite recursion
Must shrink inputEnsures base case is reached
Must return in every branchAvoids None result
Pass n - 1 not n--Don't mutate parameters

Common Base Cases

FunctionBase CaseReturn
Factorialn <= 11
Fibonaccin <= 1n
Powern == 01
GCDb == 0a
Sum of arrayi == len(arr)0

Converting Iterative → Recursive

IterativeRecursive
Loop variable (i)Function parameter (i)
Loop condition (i < n)Base case (if i >= n)
Loop bodyRecursive case
Accumulator (total)Pass as parameter or return

Exam Day Reminders

  • Read the problem: identify base case first
  • Write the function signature before the body
  • If the problem says "array of n elements", you likely need an index parameter
  • Trace your own code mentally to verify it works
  • If tracing: show every call and every return
  • For convert questions: preserve the same logic, just change the structure
Last Minute

If you forget everything, write:

if simplest case: return answer
else: return operation + recursive_call(smaller_input)