Subset sum recursively in Python

前端 未结 3 723
盖世英雄少女心
盖世英雄少女心 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:19

    I have this modified code:

    def subset_sum(seq, target):
        left, right = seq[0], seq[1:]
        return target in (0, left) or \
            (bool(right) and (subset_sum(right, target - left) or subset_sum(right, target)))
    
    def subset_sum_mem(seq, target, mem=None):
        mem = mem or {}
        key = (len(seq), target)
        if key not in mem:
            left, right = seq[0], seq[1:]
            mem[key] = target in (0, left) or \
                (bool(right) and (subset_sum_mem(right, target - left, mem) or subset_sum_mem(right, target, mem)))
        return mem[key]
    

    Can you provide some test cases this does not work for?

提交回复
热议问题