0/1knapsack背包问题:完整思维演推导过程+python
the python code:
class Item(): def __init__(self,weight,value): self.value=value self.weight=weight # test data: items_list=[Item(2,3),Item(3,4),Item(1,5),Item(5,6)] # items_list=[Item(2,3),Item(3,4),Item(1,5),Item(6,26)] def knapsack01(n, w,items_list): """[summary] Args: n (int): the number of the items to be choose (originally) w (int): the max weight the knapsack could maintain items_list (list): list of items Returns: list: two dimesion list (the last element is the max value of the knapsack) """ k = [[0 for j in range(w+1)] for i in range(n+1)] for i in range(1,n+1): for j in range(1,w+1): item=items_list[i-1] if j<item.weight: k[i][j]=k[i-1][j] else: k[i][j]=max(k[i-1][j],k[i-1][j-item.weight]+item.value) return k k=knapsack01(4,6,items_list) for line in k: print(line) print("the max value:",k[-1][-1])
the executed result:
01背包问题的推演过程
关于自底向上
tips:我们考虑从子问题的角度求解:
(往往需要理想化一些条件来使用(比如假设我们有现成的所有子问题规模的下的最优解),基于这样的条件来推导状态方程:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了