跳到主要内容

解题方法

Step 1: Identify the Base Case

The base case is the smallest possible input that can be answered directly without recursion.

ProblemBase Case
Factorial n!n <= 1 → return 1
Fibonaccin <= 1 → return n
Power x^nn == 0 → return 1
Sum of arrayi >= len(arr) → return 0
Palindromestart >= end → return True

Step 2: Design the Recursive Call

The recursive case must:

  1. Shrink the problem toward the base case
  2. Call the same function with a smaller argument
  3. Combine the result appropriately
ProblemRecursive CallCombination
Factorialfactorial(n - 1)n * ...
Fibonaccifib(n - 1) + fib(n - 2)... + ...
Powerpower(x, n - 1)x * ...
Sum of arraysum(arr, i + 1)arr[i] + ...
Palindromeis_pal(arr, s + 1, e - 1)arr[s] == arr[e] and ...

Step 3: Template Pattern

def recursive_function(parameters):
if base_condition:
return base_value
else:
# recursive case: call with smaller input
return combine(parameters[0], recursive_function(smaller_parameters))
Checklist
  • Base case returns a value (not recursive)
  • Recursive call argument is strictly smaller
  • All code paths have a return
  • Function works for edge cases (e.g. n = 0, empty array)