使用 DP 求解 "Knapsack"

Solving "Knapsack" using DP

这是我的代码:

def knapsack_dynamic(ws, vs, W):
    n = len(ws)
    K = [[0] * (W+1)] * (n+1)

    for i in range(n+1):
        for w in range(W+1):

            if i  == 0 or w == 0: # knapsack is empty or no more weight to carry
                K[i][w] = 0
            else:
                if ws[i-1] > w:
                    K[i][w] = K[i-1][w]
                else:
                    K[i][w] = max(vs[i-1] + K[i-1][w-ws[i-1]], K[i-1][w])
    return K[n][W]

测试方法如下:

maxw = 50
ws = [10, 20, 30]
vs = [60, 100, 120]
print(knapsack_dynamic(ws, vs, maxw)) # should print 220

我不确定为什么我得到的是 300 而不是 220

你能帮我弄清楚吗?

矩阵初始化时出错:

替换

K = [[0] * (W+1)] * (n+1)

来自

K = [[0] * (W+1) for i in range(n+1)]

K = [[0 for w in range(W+1)] for i in range(n+1)]

在嵌套列表上应用重复运算符 * 时,只会重复引用而不是值。

试试这个简单的例子:

m = [[0] * 4] * 3
print(m) # --> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
m[0][0] = 5
print(m) # --> [[5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0]]