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

# 简单背包问题

### 01 背包

有 n 件物品，每件有重量 w\[i] 和价值 v\[i]，背包容量为 C，每件**最多取一次**，求最大价值。

状态：`dp[j]` 表示容量为 j 时的最大价值。

```cpp
for (int i = 1; i <= n; i++)
    for (int j = C; j >= w[i]; j--)        // 逆序遍历，保证每件只用一次
        dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
cout << dp[C];
```

### 完全背包

每件物品可以取**无限次**，只需把内层循环改为**正序**：

```cpp
for (int i = 1; i <= n; i++)
    for (int j = w[i]; j <= C; j++)
        dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
```

### 为什么 01 背包要逆序

正序会让同一件物品被重复使用（变成完全背包）；逆序时 dp\[j-w\[i]] 还是“上一轮”的状态，保证只用一次。

### 空间优化

用一维数组滚动即可，无需二维 dp\[i]\[j]，空间从 O(nC) 降到 O(C)。


---

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