Python上的回溯子集和

时间:2015-04-05 10:49:37

标签: python recursion subset backtracking

所以我想要打印出初始集的所有子集,这些子集将加起来为21个。到目前为止,我只想出这个

def twentyone(array, num=21):
    if len(array) == 0:
        return None
    else:
        if array[0] == num:
            return [array[0]]
        else:
            with_v = twentyone(array[1:], (num - array[0]))
            if with_v:
                return [array[0]] + with_v
            else:
                return twentyone(array[1:], num)

确实提供了解决方案,但只提供了解决方案。如何更改它以便它将为我提供每个可能的子集。我试过做了一些改动,但它只给了我嵌套列表。你能帮忙的话,我会很高兴。

2 个答案:

答案 0 :(得分:4)

您可以创建一个递归生成器:

def twentyone(array, num=21):
    if num < 0:
        return
    if len(array) == 0:
        if num == 0:
            yield []
        return
    for solution in twentyone(array[1:], num):
        yield solution
    for solution in twentyone(array[1:], num - array[0]):
        yield [array[0]] + solution

示例:

>>> list(twentyone([5, 16, 3, 2]))
[[16, 3, 2], [5, 16]]

答案 1 :(得分:0)

如果允许使用标准Python库,这是一个较短的解决方案:

import itertools
import operator


def twentyone(array, num=21):
    subsets = reduce(operator.add, [list(itertools.combinations(array, r)) for r in range(1, 1 + len(array))])
    return [subset for subset in subsets if sum(subset) == num]


print twentyone([1, 2, 5, 6, 8, 9, 10])

结果:

[(2, 9, 10), (5, 6, 10), (1, 2, 8, 10), (1, 5, 6, 9), (2, 5, 6, 8)]