[英]Subset Sum Dynamic Programming
def subset(array, target):
sol = [[False for x in range(target + 1)] for x in range(len(array) + 1)]
for i in range(len(array)+1):
sol[i][0] = True
for i in range(1,(len(array)+1)):
for j in range(1, target+1):
if (j - array[i-1] >= 0):
sol[i][j] = sol[i-1][j] | sol[i-1][j - array[i-1]]
else:
sol[i][j] = sol[i-1][j]
printSub(sol, array, target)
return sol[len(array)][target]
def printSub(sol, array, target):
if(sol[len(array)][target]):
print("Found!")
i = len(array)
j = target
while(j!=0):
if(sol[i-1][j] == True):
i-=1
else:
print(array[i-1], end = " ")
j = j - array[i-1]
else:
print("No combination found! ")
I've a working code of the subset problem, which can print numbers if it finds a subset equal to the desired target. 我有一个子集问题的工作代码,如果它找到等于所需目标的子集,则可以打印数字。
I want to print all possible subsets for a given target, I don't understand what to change for that. 我想为给定目标打印所有可能的子集,但我不知道要为此更改什么。
How do I make it work for negative numbers? 如何使它适用于负数?
**1)**Change the printsub
function for that that is loop an i
through 1 to len(array)
and use if(sol[i][target])
instead of (sol[len(array)][target])
. ** 1)**将
printsub
函数更改为将i
从1循环到len(array)
并使用if(sol[i][target])
代替(sol[len(array)][target])
。
**2)**After the double loops- ** 2)**在两次循环之后-
for i in range(1,(len(array)+1)):
for j in range(1, target+1):
add a condition that checks if array[i-1]
is negative or not if
it is positive no need to change anything else
replace j
by target+2-j
in 添加一个条件,检查
array[i-1]
是否为负, if
为正,则无需更改任何else
将j
替换为target+2-j
if (j - array[i-1] >= 0):
sol[i][j] = sol[i-1][j] | sol[i-1][j - array[i-1]]
**3)**Here's link to same ques- Reducing time complexity of 0-1 Knapsack problem ** 3)**这里链接到相同的问题- 降低了0-1背包问题的时间复杂度
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.