完全背包问题
感谢这些朋友们的文章,给了我很大启发:
https://blog.csdn.net/songyunli1111/article/details/94778914
https://blog.csdn.net/na_beginning/article/details/62884939
https://blog.csdn.net/qq_39445165/article/details/84334970
这个问题和上篇01背包问题的区别就在于:完全背包问题中的物品数是无穷多个,也就是说对于一个物品,我可以不拿,可以拿一个、两个…只要背包空间够,理论上可以拿无限多个。
下面用几种方法来解决这个问题:
第一种使用二维数组的方法
import numpy as np
def solution(max_weight,weight,value):
dp = np.zeros((len(weight)+1,max_weight+1),dtype=int)
for i in range(1,len(weight)+1):
for j in range(1,max_weight+1):
if j >= weight[i-1]:
dp[i][j] = max(dp[i-1][j],dp[i][j-weight[i-1]] + value[i-1])
else:
dp[i][j] = dp[i-1][j]
print(dp)
return dp
def things(max_weight,dp,weight,value):
raw = len(weight)
col = max_weight
remain = dp[raw][col]
goods = []
while remain != 0:
if dp[raw][col] != dp[raw-1][col]:
remain -= value[raw-1]
col -= weight[raw-1]
goods.append(raw)
raw += 1
raw -= 1
print(goods)
数据是:
weight = [7,4,3,2]
value = [9,5,3,1]
程序的运行结果:
[[ 0 0 0 0 0 0 0 0 0 0 0]
[ 0 0 1 1 2 2 3 3 4 4 5]