【发布时间】:2019-10-16 16:20:16
【问题描述】:
对于以下子集和问题的递归解决方案(see this link),如果a 中有任何子集的和等于sum 的值,则以下代码返回true
def isSubsetSum(set,n, sum) :
# Base Cases
if (sum == 0) :
return True
if (n == 0 and sum != 0) :
return False
# If last element is greater than sum, then ignore it
if (set[n - 1] > sum) :
return isSubsetSum(set, n - 1, sum);
# else, check if sum can be obtained by any of the following
# (a) including the last element
# (b) excluding the last element
return isSubsetSum(set, n-1, sum) or isSubsetSum(set, n-1, sum-set[n-1])
set = [2, 1, 14, 12, 15, 2]
sum = 9
n = len(set)
if (isSubsetSum(set, n, sum) == True) :
print("Found a subset with given sum")
else :
print("No subset with given sum")
我怎样才能返回满足sum 的a 的索引?
另外,如何使函数对数组a 中的负整数起作用。
【问题讨论】:
标签: python numpy dynamic-programming