Number of distinct sums from non-empty groupings of (possibly very large) lists

穿精又带淫゛_ 提交于 2019-12-04 22:37:08

The next code uses dynamic programming to avoid exponential complexity (while complexity depends on the number of possible sums and coin quantity). My Python skills are weak, so optimizations might be possible.

P.S. Classic DP uses array of length=1+overall sum of all coins, here I tried with sets.

def possibleSums(coins, quantity):
    sumset = set()
    tempset = set()
    sumset.add(0)
    for ic in range(len(coins)):
        coin = coins[ic]
        for q in range(quantity[ic]):
            val = (q + 1) * coin
            for s in sumset:
                if not (s + val) in sumset:
                    tempset.add(s+val)
        sumset = sumset | tempset
        tempset.clear()
    return len(sumset) - 1

print(possibleSums([3,5], [3,2]))
print(possibleSums([5,13,19], [10000,10,2]))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!