简体   繁体   English

使用DP的python中的子集总和

[英]Subset Sum in python using DP

I'm following this link to write a DP solution for Subset problem. 我正在通过此链接为子集问题编写DP解决方案。

def subsetSum(input, target):
    row, col = len(input)+1, target+1
    db = [[False] * col] * row
    for i in range(row):
        db[i][0] = True

    for i in range(1, row):
        for j in range(1, col):
            db[i][j]=db[i-1][j]
            if db[i][j]==False and j>=input[i-1]:
                db[i][j] = db[i-1][j-input[i-1]]

    return db[i][j]

target = 5
input = [1,3,9,2]
subsetSum(input, target)

Interestingly after every iteration of " j ", db[i-1] (the previous row where we are referring to the values) is also getting updated. 有趣的是,在每次“ j ”迭代之后, db [i-1] (我们指的是值的上一行)也正在更新。 I'm really lost whats happening here. 我真的不知道这里发生了什么。 Please suggest. 请提出建议。

Please find this link for the printed statements. 请在打印的声明中找到此链接

The issue is in this line db = [[False] * col] * row . 问题在这一行db = [[False] * col] * row When you use the * operator, a copy of the original list is made that refers to the original list. 当您使用*运算符时,将创建引用原始列表的原始列表的副本。

Consider the following example: 考虑以下示例:

l = [[1]*5]*3
print(l) # prints [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
l[0][0] = 0
print(l) # prints [[0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1]]

Each inner list refers to the same object. 每个内部列表都引用相同的对象。 Thus, when the first element of the first list is changed, all lists appear to change. 因此,当第一个列表的第一个元素更改时,所有列表似乎都更改了。

To remedy this, you can use a list comprehension: 为了解决这个问题,您可以使用列表理解:

l = [[1]*5 for _ in range(3)]
print(l) # prints [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
l[0][0] = 0
print(l) # prints [[0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]

Specifically, you can replace your assignment to db with the following: 具体来说,您可以使用以下内容替换对db的分配:

db = [[False]*col for _ in range(row)] . db = [[False]*col for _ in range(row)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM