How to find all combinations that sum up to at most a constant?

后端 未结 1 1209
野的像风
野的像风 2020-12-12 06:24

Let P=[P1, P2, ..., Pk] be k positive integers and let T be a positive integer. I would like to generate all combinations that sum up

相关标签:
1条回答
  • 2020-12-12 07:21

    This is like the subset sum problem (mentioned in the comments), except that's about finding numbers summing equal to a target. You want to find numbers summing to a total less-than-or-equal to the target.

    Nonetheless, a similar approach with dynamic programming can be used:

    def subset_sum(vals, target=0):
        sums = {0: [()]}  # key=sum, value=list of subsets for the sum
        if target in sums:
            yield from sums[target]  # annoying base case
        for val in vals:
            items = sums.items()  # don't change dict size during iteration
            sums = dict(items)
            for prev_sum, prev_subsets in items:
                sum_ = prev_sum + val
                subsets = [s + (val,) for s in prev_subsets]
                sums[sum_] = sums.get(sum_, []) + subsets
                if sum_ <= target:
                    yield from subsets
    

    Demo:

    >>> for subset in subset_sum([1, 2, 3], target=4):
    ...     print(*subset, sep='+')
    ...     
    1
    2
    1+2
    3
    1+3
    
    0 讨论(0)
提交回复
热议问题