簡體   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