给定一组整数(正数或负数),如何找到这些数字的序列总和为给定值?
示例:给定一个数字列表[4,-16, 9, 33]
,我需要总和17
。我可以选择序列[4, 4, 9]
(数字可以重复使用)或[-16, 33]
。我正试图找到一种有效的方法来减少序列的长度。
就像Subset Sum Problem
(http://en.wikipedia.org/wiki/Subset_sum),但就我而言,数字可以重复使用。
它也有点像分区问题(Find all possible subsets that sum up to a given number)但在我的情况下有负值。
我目前的贪心算法如下。在每个循环中,我将尝试找到一个最小化当前总和与目标总和之间差异的数字。
integers = [-2298478782, 1527301251, 4, 4078748803, 3388759435,
1583071281, 2214591602, 1528349827, -12, 59460983,
-939524100, -1, 2315255807]
target_sum = 1997393191
difference = target_sum
chain = list()
while difference != 0:
min_abs_difference = abs(difference)
next_int = 0
found = False
for i in integers:
new_abs_diff = abs(i+difference)
if new_abs_diff < min_abs_difference:
found = True
next_int = i
min_abs_difference = new_abs_diff
if not found:
print(difference)
print(chain)
print("Cannot find an integer that makes difference smaller")
break
difference += next_int
chain.append(next_int)
print(chain)
答案 0 :(得分:1)
很可能没有提供最佳解决方案的快速算法。子集求和问题是NP完全的,问题比你的问题容易(因为你允许重复使用数字)。
鉴于问题是NP完全的,我认为你应该专注于改进你当前的算法或用C语言等更快的语言重写它。然后你可以用Python调用你的C代码。
答案 1 :(得分:1)
由于显然至少是NP完全问题,你可以考虑将其公式化为混合整数线性规划问题。
Minimize summation( Xi ) // Xi = number of times the array element Ai is used.
Subject To
summation( Ai*Xi ) = S.
Xi >= 0 { Xi are all integers }
您可以使用任何解算器解决它。