【动态规划】 解决背包问题 Python
背包问题
背包问题
现在有3个物品 篮球 1kg 1000元 吉他 3kg 2000元 单反 4kg 2500元
有1个背包 重4kg
问怎么拿物品价值最大
运用 动态规划DP 来解决此问题
方法
代码【源码】——思路来自 麻省理工背包问题
def backpack(memory, item_weight, values, last_weight, index):
'''
memory : 如果是已经计算过得分支 则直接返回
此时是如果有很多个物品 可能会出现多个选择A物品之后的物品 剩余x千克的情况
此时可以避免重复计算,直接返回价值最大值
dic
item_weight : 所有物品重量 list
values : 所有物品价值 list
last_weight : 背包剩余重量 float
index : 物品下标 int
'''
# print('0 :',index, last_weight)
try:
# 如果此时是已经计算过得 则直接返回
# key 为 (index, last_weight) 如果物品很多则会有多次出现相同的情况
memory[(index, last_weight)]
except:
# 如果没有计算过 就重新计算一次到底
if index == 0:
# DP 动态规划 降到底层 自底向上的计算
# 判断底层的东西的位置还有没有 判断是否可以装东西 帮助跳出函数循环
if item_weight[index] <= last_weight:
return values[index]
else:
return 0
# print('1 :',index, last_weight)
# 寻找可以装的东西, 从底层开始找
without_l = backpack(memory, item_weight, values, last_weight, index - 1)
# print('2 :',index, last_weight)
# 如果 当前物品的重量 大于 剩余重量 返回 背包内历史查找的最大的价值
if item_weight[index] > last_weight:
return without_l
else:
# 如果小于 说明还能放入背包 那么得到剩余背包重量 再继续寻找东西
# print('继续装')
with_l = values[index] + backpack(memory, item_weight, values, last_weight - item_weight[index], index - 1)
# 比较最大值
maxvalue = max(without_l, with_l)
# 储存当前节点的搜索情况
memory[(index, last_weight)] = maxvalue
# print('3: ',index, last_weight, memory)
return maxvalue
测试
item_weight = [1, 3, 4]
values = [1000, 2000, 2500]
backpack({}, item_weight, values, 4, len(item_weight) - 1)
# 3000