给定一个数字列表,如何创建所有总和的组合并返回这些总和的列表

时间:2021-05-28 23:52:33

标签: python algorithm backtracking

假设我们有一个数字列表 [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]

3 个答案:

答案 0 :(得分:2)

使用 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]

答案 1 :(得分:2)

使用 itertools.permutations

>>> import itertools
>>> nums = [1, 2, 3]
>>> [sum(p) for n in range(1, len(nums)+1) for p in itertools.permutations(nums, n)]
[1, 2, 3, 3, 4, 3, 5, 4, 5, 6, 6, 6, 6, 6, 6]

如果您想确切地查看 permutations 正在做什么而不只是查看最终和,您可以使用 mapjoin 做一些有趣的事情:

>>> [f"{'+'.join(map(str, p))}={sum(p)}" for n in range(1, len(nums)+1) for p in itertools.permutations(nums, n)]
['1=1', '2=2', '3=3', '1+2=3', '1+3=4', '2+1=3', '2+3=5', '3+1=4', '3+2=5', '1+2+3=6', '1+3+2=6', '2+1+3=6', '2+3+1=6', '3+1+2=6', '3+2+1=6']

答案 2 :(得分:2)

这是递归问题的一个很好的例子。

要解决这个问题,您需要一个调用自身并在给定条件下停止的函数。

const getResults = (numbers, usedNumbers, results) => {
  if (usedNumbers.length >= numbers.length) return;

  numbers.forEach(number => {
    if (usedNumbers.includes(number)) return;

    const result = usedNumbers.reduce((acc, curr) => acc + curr, number);
    console.log(`${[...usedNumbers, number].join(' + ')} = ${result}`)
    results.push(result);
  });

  numbers.forEach(number => {
    if (! usedNumbers.includes(number)) getResults(numbers, [...usedNumbers, number], results);
  })
};

const numbers = [1,2,3];
const results = [];
numbers.forEach(number => {
  results.push(number);
  console.log(`${number} = ${number}`)
  getResults(numbers, [number], results);
});

console.log(results);