File tree Expand file tree Collapse file tree 1 file changed +37
-1
lines changed Expand file tree Collapse file tree 1 file changed +37
-1
lines changed Original file line number Diff line number Diff line change @@ -179,9 +179,45 @@ int main() {
179
179
180
180
Java:
181
181
182
-
183
182
Python:
184
183
184
+ ``` python3
185
+ # 先遍历物品,再遍历背包
186
+ def test_complete_pack1 ():
187
+ weight = [1 , 3 , 4 ]
188
+ value = [15 , 20 , 30 ]
189
+ bag_weight = 4
190
+
191
+ dp = [0 ]* (bag_weight + 1 )
192
+
193
+ for i in range (len (weight)):
194
+ for j in range (weight[i], bag_weight + 1 ):
195
+ dp[j] = max (dp[j], dp[j - weight[i]] + value[i])
196
+
197
+ print (dp[bag_weight])
198
+
199
+ # 先遍历背包,再遍历物品
200
+ def test_complete_pack2 ():
201
+ weight = [1 , 3 , 4 ]
202
+ value = [15 , 20 , 30 ]
203
+ bag_weight = 4
204
+
205
+ dp = [0 ]* (bag_weight + 1 )
206
+
207
+ for j in range (bag_weight + 1 ):
208
+ for i in range (len (weight)):
209
+ if j >= weight[i]: dp[j] = max (dp[j], dp[j - weight[i]] + value[i])
210
+
211
+ print (dp[bag_weight])
212
+
213
+
214
+ if __name__ == ' __main__' :
215
+ test_complete_pack1()
216
+ test_complete_pack2()
217
+ ```
218
+
219
+
220
+
185
221
186
222
Go:
187
223
You can’t perform that action at this time.
0 commit comments