Skip to content

Commit 3543594

Browse files
authored
Update 背包理论基础01背包-1.md
1 parent 4f9c892 commit 3543594

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

problems/背包理论基础01背包-1.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ dp[0][j],即:i为0,存放编号0的物品的时候,各个容量的背包
118118

119119
代码初始化如下:
120120

121-
```
121+
```CPP
122122
for (int j = 0 ; j < weight[0]; j++) { // 当然这一步,如果把dp数组预先初始化为0了,这一步就可以省略,但很多同学应该没有想清楚这一点。
123123
dp[0][j] = 0;
124124
}
@@ -147,7 +147,7 @@ dp[0][j] 和 dp[i][0] 都已经初始化了,那么其他下标应该初始化
147147

148148
最后初始化代码如下:
149149

150-
```
150+
```CPP
151151
// 初始化 dp
152152
vector<vector<int>> dp(weight.size(), vector<int>(bagweight + 1, 0));
153153
for (int j = weight[0]; j <= bagweight; j++) {
@@ -171,7 +171,7 @@ for (int j = weight[0]; j <= bagweight; j++) {
171171
172172
那么我先给出先遍历物品,然后遍历背包重量的代码。
173173
174-
```
174+
```CPP
175175
// weight数组的大小 就是物品个数
176176
for(int i = 1; i < weight.size(); i++) { // 遍历物品
177177
for(int j = 0; j <= bagweight; j++) { // 遍历背包容量
@@ -186,7 +186,7 @@ for(int i = 1; i < weight.size(); i++) { // 遍历物品
186186

187187
例如这样:
188188

189-
```
189+
```CPP
190190
// weight数组的大小 就是物品个数
191191
for(int j = 0; j <= bagweight; j++) { // 遍历背包容量
192192
for(int i = 1; i < weight.size(); i++) { // 遍历物品
@@ -232,7 +232,7 @@ dp[i-1][j]和dp[i - 1][j - weight[i]] 都在dp[i][j]的左上角方向(包括
232232

233233
主要就是自己没有动手推导一下dp数组的演变过程,如果推导明白了,代码写出来就算有问题,只要把dp数组打印出来,对比一下和自己推导的有什么差异,很快就可以发现问题了。
234234

235-
```cpp
235+
```CPP
236236
void test_2_wei_bag_problem1() {
237237
vector<int> weight = {1, 3, 4};
238238
vector<int> value = {15, 20, 30};

0 commit comments

Comments
 (0)