python 学习 0-1背包问题

import numpy as np
weight = [15,5,16,7,1,15,6,3]
# weight = [3,2,1]
weight_most = 19
# weight_most = 5
def bag_0_1(weight, weight_most):  # return max value
    num = len(weight)
    weight.insert(0, 0)  # 前0件要用
    bag = np.zeros((num + 1, weight_most + 1), dtype=np.int32)  # 下标从零开始
    for i in range(1, num + 1):
        for j in range(1, weight_most + 1):
            if weight[i] <= j:
                bag[i][j] = max(bag[i - 1][j - weight[i]]+ weight[i] , bag[i - 1][j])
                # print(bag[i][j])
            else:
                bag[i][j] = bag[i - 1][j]
    return bag
    # print(bag)

result = bag_0_1(weight, weight_most)
print(result)

猜你喜欢

转载自blog.csdn.net/u011451186/article/details/82830575