简体   繁体   English

Python中的子集总和(动态编程) - 复杂性问题

[英]Subset sum (dynamic programming) in Python - complexity problem

I have a problem with some implementation of a function that solves the problem of a subset sum in Python.我对解决 Python 中子集总和问题的函数的某些实现有问题。

We have dynamic programming here, so the complexity should be polynomial.我们这里有动态规划,所以复杂度应该是多项式的。

The problem is that if the size of set grows linearly and the size of the numbers also increases linearly (of course it is not a logarithm of numbers) then the code execution time can grow exponentially.问题是如果集合的大小线性增长并且数字的大小也线性增长(当然它不是数字的对数)那么代码执行时间会呈指数增长。

My guess is that this may be due to a particular implementation.我的猜测是这可能是由于特定的实现。 Is it possible to improve it somehow?有没有可能以某种方式改进它?

Code in Python: Python中的代码:

def subsetsum(array,num):

    if num == 0 or num < 1:
        return None
    elif len(array) == 0:
        return None
    else:
        if array[0] == num:
            return [array[0]]
        else:
            with_v = subsetsum(array[1:],(num - array[0])) 
            if with_v:
                return [array[0]] + with_v
            else:
                return subsetsum(array[1:],num)

You're using slices to pass suffixes of array , this will make a copy which has linear runtime.您正在使用 slice 来传递array后缀,这将制作一个具有线性运行时间的副本。 To avoid that you can pass indices instead.为避免这种情况,您可以改为传递索引。 Another advantage is that indices are hashable, so you can cache (or memoize ) and avoid recomputing answers:另一个优点是索引是可散列的,因此您可以缓存(或memoize )并避免重新计算答案:

from functools import lru_cache

def ssum(array, N):
    @lru_cache(maxsize=None)
    def subsetsum(idx, num):
        if num < 1 or idx >= len(array):
            return frozenset()
        if array[idx] == num:
            return frozenset([idx])
        with_v = subsetsum(idx + 1, num - array[idx])
        if with_v:
            return with_v | frozenset([idx])
        else:
            return subsetsum(idx + 1, num)
    return list(array[i] for i in subsetsum(0, N))
>>> ssum([1,1,2], 4)
[1, 1, 2]

Unfortunately, there's still the cost of copying the answer obtained from the suffix不幸的是,仍然存在复制从后缀获得的答案的成本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM