如何生成allowed_ints
的組合列表,總和爲goal
?受限整數組合的組合
例子:
allowed_ints=[1,2], goal=4
combinations = [[1,1,1,1],[1,1,2],[2,1,1],[2,2],[1,2,1]]
allowed_ints=[5, 6], goal=13
combinations = []
我到目前爲止已經取得了哪些不工作。
def combinations(allowed_ints, goal):
if goal > 0:
for i in allowed_ints:
for p in combinations(allowed_ints, goal-i):
yield [i] + p
else:
yield []
print list(combinations([1, 2],3))
[[1, 1, 1], [1, 1, 2], [1, 2], [2, 1], [2, 2]] # not what I want
檢查您是否超過「目標」的閾值。 –
組合完成後()? –
你可以,但爲什麼推遲任務... –