> 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/recurrence.md).

# 递推

### 什么是递推

递推是从**已知的初始条件**出发，按某种规律（递推式）一步步推出后续结果。相比递归，递推一般用循环实现，效率更高。

### 典型例子：斐波那契数列

`f(1)=1, f(2)=1, f(n)=f(n-1)+f(n-2)`

```cpp
long long f[100];
f[1] = f[2] = 1;
for (int i = 3; i <= n; i++)
    f[i] = f[i - 1] + f[i - 2];
cout << f[n];
```

### 典型例子：爬楼梯

每次走 1 或 2 级，走到第 n 级有多少种走法？`f(n) = f(n-1) + f(n-2)`。

### 递推 vs 递归

|    | 递推      | 递归      |
| -- | ------- | ------- |
| 实现 | 循环，从前往后 | 函数自调用   |
| 效率 | 高       | 可能有重复计算 |
| 思路 | 由小推大    | 由大化小    |

### 推导递推式的步骤

1. 确定状态含义（f\[i] 表示什么）；
2. 确定初始值（如 f\[1]、f\[2]）；
3. 找出 f\[i] 与前面项的关系；
4. 用循环从小到大计算。

> 递推也是动态规划的基础，很多 DP 问题本质上就是递推。


---

# 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/recurrence.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.
