不同的方法。
1 找出所有加起来为零的权重序列,按顺序排列。
例如,这是一些可能性(使用整数以减少输入):
[0, 0, 0, 0, 0]
[-4, 0, 0, +2, +2]
[-4, 0, 0, 0, +4]
[-4, +4, 0, 0, 0] 是不正确的,因为权重没有按顺序选择。
2 对上面得到的结果进行排列组合,因为排列组合也会加起来为零。
这就是你可以得到 [-4, 0, 0, 0, +4] 和 [-4, +4, 0, 0, 0] 的地方。
好了,我有点懒。我将用伪代码/注释代码来解决这个问题。递归不太强,这东西太棘手了,无法快速编码,而且我怀疑这种类型的解决方案是否可扩展到50个。
即我认为自己可能是错误的,但这可能会给别人带来想法。
def find_solution(weights, length, last_pick, target_sum):
solutions = []
if length > 1:
if last_pick > weights[0]:
weights = [w for w in weights if w >= last_pick]
for weight in weights:
child_target_sum = target_sum + weight
if child_target_sum <= 0:
break
child_solutions = find_solution(weights, length=length-1, last_pick=weight, target_sum=child_target_sum)
[solutions.append([weight] + child ) for child in child_solutions if child_solution]
else:
if target_sum in weights:
return [[target_sum]]
return solutions
weights = list(set(weights))
weights.sort()
solutions = find_solutions(weights, len(solution), -999999999, 0)
permutated = []
for solution in solutions:
permutated.extend(itertools.permutations(solution))
5 ** 25
个要迭代的事情,大约是10 ** 18
。 - Steve Jessop5**25
的数量级是10**17
而不是10**18
。但是10**18
仍然是一个非常宽松的下限,因为平均而言,在给定前25个项目的情况下,选择最后25个项目的方法远远超过三种。 - Steve Jessop