Subset sum recursively in Python

前端 未结 3 718
盖世英雄少女心
盖世英雄少女心 2021-01-19 00:02

I will be happy to get some help.

I have the following problem:

I\'m given a list of numbers seq and a target number and I need to write 2 thing

3条回答
  •  被撕碎了的回忆
    2021-01-19 00:30

    Just for reference, here's a solution using dynamic programming:

    def positive_negative_sums(seq):
        P, N = 0, 0
        for e in seq:
            if e >= 0:
                P += e
            else:
                N += e
        return P, N
    
    def subset_sum(seq, s=0):
        P, N = positive_negative_sums(seq)
        if not seq or s < N or s > P:
            return False
        n, m = len(seq), P - N + 1
        table = [[False] * m for x in xrange(n)]
        table[0][seq[0]] = True
        for i in xrange(1, n):
            for j in xrange(N, P+1):
                table[i][j] = seq[i] == j or table[i-1][j] or table[i-1][j-seq[i]]
        return table[n-1][s]
    

提交回复
热议问题