> 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/algorithms/dynamic-programming.md).

# 动态规划入门（一维 DP）

### 核心思想

动态规划（DP）通过把问题拆成**重叠子问题**，保存子问题的答案（**记忆化**），避免重复计算，从而高效求解。

### 使用条件

* **最优子结构**：整体最优由子问题最优构成
* **重叠子问题**：子问题被重复使用
* **无后效性**：当前状态确定后，之后的决策与如何到达该状态无关

### 解题步骤

1. 定义**状态**（dp\[i] 表示什么）
2. 确定**初始值**
3. 推导**状态转移方程**
4. 确定**遍历顺序**与答案

### 例子：数字三角形（最大路径和）

```cpp
// dp[i][j] = a[i][j] + max(dp[i+1][j], dp[i+1][j+1])
for (int j = 1; j <= n; j++) dp[n][j] = a[n][j];
for (int i = n - 1; i >= 1; i--)
    for (int j = 1; j <= i; j++)
        dp[i][j] = a[i][j] + max(dp[i + 1][j], dp[i + 1][j + 1]);
cout << dp[1][1];
```

### 例子：最长不下降子序列长度（LIS 基础版）

```cpp
for (int i = 1; i <= n; i++) {
    dp[i] = 1;
    for (int j = 1; j < i; j++)
        if (a[j] <= a[i]) dp[i] = max(dp[i], dp[j] + 1);
}
```

### 与递推的关系

递推是从已知推未知，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/algorithms/dynamic-programming.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.
