Skip to content

Commit 9c0fe0f

Browse files
committed
Update 背包问题理论基础完全背包.md
添加 python3 版本代码
1 parent b960ff0 commit 9c0fe0f

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

problems/背包问题理论基础完全背包.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,45 @@ int main() {
179179

180180
Java:
181181

182-
183182
Python:
184183

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+
185221

186222
Go:
187223

0 commit comments

Comments
 (0)