版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AivenZhong/article/details/88959875
0-1背包问题:给定一组物品,每种物品都有自己的重量和价格,在限定的总重量内,我们如何选择,才能使得物品的总价格最高。
这里记录下python的模板
def dp(weight, count, weights, costs):
"""
动态规划模板,时间复杂度O(weight * count), 空间复杂度O(weight)
:param weight: 背包最大能装的重量
:param count: 物品数量
:param weights: 每件物品的重量
:param costs: 每件物品的价值
:return: 背包装下的最大价值
"""
preline, curline = [0] * (weight + 1), [0] * (weight + 1)
for i in range(count):
for j in range(weight + 1):
if weights[i] <= j:
curline[j] = max(preline[j], costs[i] + preline[j - weights[i]])
preline = curline[:]
return curline[weight]
# count:物品数量; weight:背包总重量; costs: 每件物品的价值; weight:每件物品的重量
count, weight = 5, 10
costs = [200, 300, 350, 400, 500]
weights = [3, 4, 3, 5, 5]
print(dp(weight, count, weights, costs))
# 答案是900
# 动态规划填表过程
# 0 0 0 200 200 200 200 200 200 200 200
# 0 0 0 200 300 300 300 500 500 500 500
# 0 0 0 350 350 350 550 650 650 650 850
# 0 0 0 350 350 400 550 650 750 750 850
# 0 0 0 350 350 500 550 650 850 850 900