Recursion
一句话解释
Recursion 是当 函数 calls 它自己到 解决 smaller version 的相同 problem 直到基础情况是 reached.
用大白话说
Recursion 是一种technique where a function solves a problem by calling itself with a smaller or simpler input。 Each recursive call breaks the problem down until it reaches a base case — a simple version that can be solved directly without recursion.
Think of recursion like Russian nesting dolls. You open a doll to find a smaller doll inside, and keep opening until you reach the smallest doll that cannot be opened further. That smallest doll is the base case.
Recursion is elegant for problems that have a self-similar structure: factorial, Fibonacci, tree traversal, directory listing. However, each recursive call adds to the call stack, so deep recursion can cause a stack overflow. Iteration is usually more efficient for simple repetition.
示例
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
console.log(factorial(5)); // 120factorial(5) = 5 * factorial(4) = 5 * 4 * factorial(3) = ... = 5 * 4 * 3 * 2 * 1 = 120. 基础情况 (n <= 1) 停止 recursion.
常见混淆
容易混淆的对象: 循环
关键区别: 循环 repeats code using iteration (for/虽然); recursion repeats 通过函数 calling 它自己. 循环是 通常更多 efficient; recursion 能是 clearer for 树-structured problems.
相关术语
相关资源
相关课程
- Recursion
学习关于 recursive 函数.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。