原理不说了,参考博客:https://blog.csdn.net/mu399/article/details/7722810
上代码:
import numpy as np
import pandas as pd
weights = np.array([0, 2, 2, 6, 5, 4])
values = np.array([0, 6, 3, 5, 4, 6])
capacity = 10
num_items = len(weights)
table = np.zeros(shape=(num_items , capacity + 1), dtype=int)
current_value = 0
for i in range(1, num_items):
for j in range(1, capacity + 1):
if j < weights[i]:
table[i, j] = table[i - 1, j]
else:
current_value = table[i - 1, j - weights[i]] + values[i]
table[i, j] = max(table[i-1, j], current_value)
df = pd.DataFrame(data=table[1:, 1:], index=range(1, num_items), columns=range(1, capacity + 1))
print(df)
运行后: