Understanding recursion and stack frame management理解递归原理与函数栈帧管理
Recursion is a technique where a function calls itself (directly or indirectly) to solve a problem by breaking it into smaller subproblems, until reaching a base case. 递归是一种编程技巧,函数直接或间接调用自身来解决问题。它将复杂问题分解为更小的同类问题,直至达到基准情况。
factorial(5)
├── factorial(4)
│ ├── factorial(3)
│ │ ├── factorial(2)
│ │ │ ├── factorial(1)
│ │ │ │ └── return 1
│ │ │ └── return 1 * 1 = 1
│ │ └── return 2 * 1 = 2
│ └── return 3 * 2 = 6
└── return 4 * 6 = 24
A recursion must have one or more base cases; otherwise, it results in infinite recursion and stack overflow. 递归必须有一个或多个终止条件,否则会导致无限递归和栈溢出。
A recursive function calls itself and must move arguments towards the base case.函数调用自身,但参数必须向基准情况逐步接近。
Each recursive call creates a new stack frame with parameters, locals, and return address.每次递归调用都会创建新的栈帧,包含参数、局部变量和返回地址。
Each function call creates a stack frame on the stack that includes:每次函数调用都会在栈上创建一个栈帧,包含:
调用前: [main]
调用function_a: [main] -> [function_a: x=10]
调用function_b: [main] -> [function_a: x=10] -> [function_b: y=20]
function_b返回: [main] -> [function_a: x=10]
function_a返回: [main]
Let’s implement a classic Week 1 recursion exercise — a countdown launch program:让我们实现Week 1的经典递归练习——倒计时发射程序:
If recursion depth grows too large, the stack may overflow and crash. On Linux, default stack size is typically a few MB.当递归深度过大时,会耗尽栈空间导致程序崩溃。Linux系统默认栈大小通常为几MB。
Implement Fibonacci with recursion: F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)用递归实现斐波那契数列:F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2)
Answer:答案:
Use recursion to sum an array without loops:用递归实现数组求和,不使用循环:
Answer:答案:
Recursion is a key concept in CS. In this module, you learned:递归是计算机科学中的重要概念,本周我们学习了:
After mastering recursion, you’ve completed Week 1 core content. Next, explore advanced string handling and data structures.掌握了递归后,我们已经完成了Week 1的核心内容。接下来可以探索更高级的字符串处理和数据结构。