首页 > 解决方案 > 给定一个数字列表,如何创建总和的所有组合并返回这些总和的列表

问题描述

让我们假设我们有一个数字列表 [1,2,3],我们必须将所有可能的元素总和组合附加到一个数组中并返回该数组?

如何获得以下金额

1 = 1 (the first element so simply add it to the ans array)
1 + 2 = 3
1 + 3 = 4
1 + 2 + 3 = 6
1 + 3 + 2 = 6
2 = 2 (second element so simply add it to ans array)
2 + 1 = 3
2 + 3 = 5
2 + 1 + 3 = 6
2 + 3 + 1 = 6
3 + 1 = 4
3 = 3 (third element so simply add it to ans array)
3 + 1 = 4
3 + 2 = 5
3 + 1 + 2 = 6
3 + 2 + 1 = 6

所以我们的最终数组看起来像 [1,3,4,6,6,2,3,5,6,6,3,4,5,6,6]

标签: pythonalgorithmbacktracking

解决方案


使用itertools

import itertools

nums = [1,2,3]
results = []

def split(a, n):
    k, m = divmod(len(a), n)
    return [a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n)]
        
for i in range(len(nums)):
    results.append(split(list(map(sum,itertools.permutations(nums,i+1))),len(nums)))

results = zip(*results)
results = list(itertools.chain.from_iterable(itertools.chain.from_iterable(results)))

print(results)
>>> [1, 3, 4, 6, 6, 2, 3, 5, 6, 6, 3, 4, 5, 6, 6]

推荐阅读