> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/functions/recursion-1-10.md).

# 递归输出 1-10

### 递归三要素

1. **终止条件**（边界）：什么时候停止
2. **递归调用**：把问题规模变小
3. **返回/处理**：由子问题结果得到当前结果

### 递归输出 1\~n

```cpp
void print(int n) {
    if (n == 0) return;   // 终止条件
    print(n - 1);         // 先处理小的
    cout << n << " ";     // 再输出（正序）
}

void printReverse(int n) {
    if (n == 0) return;
    cout << n << " ";     // 先输出（倒序）
    printReverse(n - 1);
}
```

`print(10)` 输出 `1 2 3 ... 10`；`printReverse(10)` 输出 `10 9 ... 1`。

### 递归与递推

|    | 递归       | 递推    |
| -- | -------- | ----- |
| 方向 | 由大化小     | 由小推大  |
| 实现 | 函数自调用    | 循环    |
| 风险 | 栈溢出、重复计算 | 无明显风险 |

### 递归求阶乘 / 斐波那契

```cpp
long long fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }

long long fib(int n) {
    if (n <= 2) return 1;
    return fib(n - 1) + fib(n - 2);   // 直接递归会重复计算，n 大时很慢
}
```

### 优化

* 用**记忆化**保存已算过的结果，避免重复。
* 能改递推的尽量改递推，效率更高。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/functions/recursion-1-10.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
