跟随carl代码随想录刷题
语言:python
⭐️每种物品都有无数件。
⭐️遍历顺序:
内循环
是从大到小遍历的
二维dp数组
的两个for遍历的先后顺序可以颠倒。一维dp数组
的两个for循环先后顺序必须是先遍历物品
,再遍历背包容量
。内循环
是从小到大遍历的
一维dp数组
两个for循环的嵌套顺序不重要。
def test_complete_pack1():
weight = [1, 3, 4]
value = [15, 20, 30]
bag_weight = 4
# 初始化
dp = [0] * (bag_weight + 1)
# 先遍历物品
for i in range(len(weight)):
# 再遍历背包
for j in range(weight[i], bag_weight + 1):
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
print(dp[bag_weight])
def test_complete_pack2():
weight = [1, 3, 4]
value = [15, 20, 30]
bag_weight = 4
# 初始化
dp = [0] * (bag_weight + 1)
# 先遍历背包
for j in range(bag_weight + 1):
# 再遍历物品
for i in range(len(weight)):
if j >= weight[i]:
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
print(dp[bag_weight])