> 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/advanced-dp/lcs.md).

# 最长公共子序列（LCS）

### 问题

求两个序列的最长公共子序列长度。

### DP O(nm)

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

### 转移含义

* 若 a\[i] == b\[j]：可以接在 dp\[i-1]\[j-1] 后。
* 否则：舍弃 a 或 b 的最后一个，取较优。

### 输出具体序列

从 dp\[n]\[m] 回溯：

```cpp
string s;
int i = n, j = m;
while (i > 0 && j > 0) {
    if (a[i] == b[j]) { s += a[i]; i--; j--; }
    else if (dp[i-1][j] >= dp[i][j-1]) i--;
    else j--;
}
reverse(s.begin(), s.end());
```

### 对比

* LIS：一个序列，O(n log n)
* LCS：两个序列，O(nm)，空间可用滚动数组优化到 O(m)


---

# 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/advanced-dp/lcs.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.
