【问题标题】:Finding out the possible combination of a given number找出给定数字的可能组合
【发布时间】:2021-03-17 15:13:58
【问题描述】:

使用下面的代码找出给定数字的可能组合。 Finding all possible combinations of numbers to reach a given sum

但是,如果总体中存在负值,则此公式将不起作用。是否可以进行任何修改以解决此问题?

提前致谢


def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target:
        print("sum(%s)=%s" % (partial, target))
    if s >= target:
        return  # if we reach the number why bother to continue

    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])


if __name__ == "__main__":
    subset_sum([-17896,-4774,-1472,701,912,2848,3431,3966], -12284)

【问题讨论】:

    标签: python python-3.x combinations


    【解决方案1】:

    乍一看:第二次检查if s >= target: return 仅适用于正输入情况。当输入中有负值时,部分总和可能大于目标。只需禁用此检查。

    sum([-17896, -4774, -1472, 701, 912, 2848, 3431, 3966])=-12284
    

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      相关资源
      最近更新 更多