背包问题

动态规划 Python 3 实现:

capacity = 7
num = 4

optimal_matrix = [[0 for x in range(capacity + 1)] for y in range(num + 1)]
weight = [0, 1, 3, 4, 5]
value = [0, 1, 4, 5, 7]

for c in range(capacity + 1):
    for n in range(1, num + 1):
        if weight[n] <= c:
            optimal_matrix[n][c] = max(value[n]+ optimal_matrix[n - 1][c - weight[n]], optimal_matrix[n - 1][c])
        else:
            optimal_matrix[n][c] = optimal_matrix[n - 1][c]

print("max_value: ", optimal_matrix[num][capacity])

c = capacity
n = num

while n > 0:
    if optimal_matrix[n][c] == optimal_matrix[n - 1][c]:
        n = n - 1
    else:
        print("index:", n, "weight:", weight[n], "value:", value[n])
        c = c - weight[n]
        n = n - 1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容