解决"背包"使用DP

时间:2018-04-12 12:12:21

标签: python algorithm computer-science np

这是我的代码:

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

你能帮我解决一下吗?

1 个答案:

答案 0 :(得分:1)

在矩阵初始化期间发生错误:

替换

$.ajax({
    type: 'POST',
    url: 'xxx',
    success: function(response) {
      console.log(response);
      if (response == "1") {
        alert("ONE");
      }
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }
});

通过

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)] 时,只重复引用而不是值。

试试这个简单的例子:

*