[英]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.