繁体   English   中英

生成所有可能的组合效率低下

[英]Generating all possible combinations inefficient

代码生成数字列表的所有可能组合,并获取具有特定总和的组合:

combos = []

for each in combinations_with_replacement(list, number):
    if sum(list(map(int, each))) == particular_number:
        combos.append(list(map(int, each)))

代码运行正常。 但是问题是,如果在combinations_with_replacement函数中的number参数大于8,则将花费大量时间。 有没有可以替代我的逻辑的优化方法?

首先,退出重复工作。

  • 进入循环之前,将列表元素转换为整数。
  • 组合已经在一个元组中了; 您是否真的需要将其转换为combos列表?
  • 与其生成各种列表长度的所有组合,不如尝试使用“目标总和”搜索找到的递归解决方案。 这将大大减少尝试列表的数量。

递归解决方案的基本思想是:

# Given: remaining target sum and list of numbers (lon) to use
if target = 0:
    return []
if target < 0 or len(lon) == 0:
    return None

if target >= lon[0]:
    # add one of the first number; recur
    result = sum_to_target(target - lon[0], lon)
    return result + [lon[0]] if result else None

# Done with this number; try the rest of the list
result = sum_to_target(target, lon[1:])
return result if result else None

尝试使用列表的第一个数字或不使用第一个数字的所有步骤。 如果超出目标或数字用完,则失败。 如果您精确地达到了目标,那么您将成功:在爬回调用堆栈时建立有效的一组数字。

请注意,我已经将连接所有解决方案的问题留给了您……还有一些调试和边界细节。

暂无
暂无

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

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