Search CTRL + K

Recursion

递归(Recursion) 在数学和计算机科学中是指在函数的定义中使用函数自身的方法,在计算机科学中还额外指一种通过重复将问题分解为同类的子问题而解决问题的方法。[1]

递归使得代码逻辑结构清晰,可读性强;但递归使用栈来存储临时变量,层数过多时会有栈溢出风险。递归性能一定不如递推,但它能节约程序员的时间。

特征

递归的最重要两个特征是“结束条件”和“自我调用”。

int func(传入数值) {
  if (终止条件) return 最小子问题解;
  return func(缩小规模);
}

要点

明白一个函数的作用并相信它能完成这个任务,千万不要跳进这个函数里面企图探究更多细节, 否则就会陷入无穷的细节无法自拔,人脑能压几个栈啊。[1:1]

Why use recursion?

Recursion is used when it makes the solution clearer. There’s no performance benefit to using recursion; in fact, loops are sometimes better for performance.[2]

Base case and recursive case

When you write a recursive function, you have to tell it when to stop recursing. That’s why every recursive function has two parts: the base case and the recursive case. The recursive case is when the function calls itself. The base case is when the function doesn’t call itself again, so it doesn’t go into an infinite loop.[2:1]


  1. https://oi-wiki.org/basic/divide-and-conquer/#递归 ↩︎ ↩︎

  2. Bhargava, Aditya Y. “Grokking Algorithms,” n.d. ↩︎ ↩︎