我想修改Finding all possible combinations of numbers to reach a given sum中的subset_sum()python函数,以便:
它允许重复(排列)而不是组合
它只考虑给定长度的置换
我已经成功地完成了2,但我需要帮助1:

def subset_sum(numbers, target, length, partial=[]):
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target and len(partial) == length:
        print(f"sum({partial})={target}")
    if s >= target:
        return  # if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i+1:]
        subset_sum(remaining, target, length, partial + [n])

所需输出应为:
>>> subset_sum([3,9,8,4,5,7,10],target=15,length=3)
sum([3, 8, 4])=15
sum([3, 4, 8])=15
sum([4, 3, 8])=15
sum([4, 8, 3])=15
sum([8, 3, 4])=15
sum([8, 4, 3])=15
sum([3, 5, 7])=15
sum([3, 7, 5])=15
sum([5, 3, 7])=15
sum([5, 7, 3])=15
sum([7, 3, 5])=15
sum([7, 5, 3])=15

最佳答案

既然您已经解决了在每个等价组中标识一个解决方案的问题,我的建议是:不要更改该算法。相反,利用itertools.permutations生成这些项:

return list(itertools.permutations(numbers))

关于python - 查找固定长度的数字的所有可能排列以达到给定的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52999207/

10-12 21:46