我希望能夠找到進入目標的最小號碼。尋找離開最小剩餘部分的最大號碼
例如:
target = 100
vals = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137]
from itertools import combinations
def subsets_with_sum(lst, target, with_replacement=False):
x = 0 if with_replacement else 1
def _a(idx, l, r, t):
if t == sum(l): r.append(l)
elif t < sum(l): return
for u in range(idx, len(lst)):
_a(u + x, l + [lst[u]], r, t)
return r
return _a(0, [], [], target)
如果我要輸入:
subsets_with_sum(vals, 270, False)
入殼,我將輸出:
[[57, 99, 114]]
然而,如果我輸入:
subsets_with_sum(vals, 239, False)
入殼,我將輸出:
[]
相反,我想輸出進入目標人數最多: [137, 101]
留下剩餘1
有沒有辦法做到這個?
感謝您的輸入! :) –
你能告訴我,如果這更快或下面的Ankush提供的方法更快?或者告訴我如何解決問題? –
@SyedArafatQureshi 1.要查看哪一個更快,您可以在同一個大輸入上運行。 – Gassa