[英]All possible change combinations
我正在嘗試 output 一個列表列表,其中包含給定數量和硬幣的所有可能的變化組合。 例如 - 給定金額 6 和硬幣 = [1,5,10] 我會得到:
[[1,1,1,1,1,1],
[1,5],
[5,1]]
我寫了一些打印正確解決方案的東西,但我不知道如何將 function 轉換為 output 列表格式的解決方案
def possible_change(n,p=[],coins = [1,5,10]):
if n == 0:
print(p)
return p
else:
for c in coins:
if n - c >= 0:
possible_change(n-c,p+[c],coins=coins)
possible_change(6,coins=[1,5,10])
如何讓 function 返回實際列表?
而不是那些打印語句,只需填充一個全局列表。
sols = []
def possible_change(n,p=[],coins = [1,5,10]):
if n == 0:
global sols
sols.append(p)
else:
for c in coins:
if n - c >= 0:
possible_change(n-c,p+[c],coins=coins)
possible_change(6,coins=[1,5,10])
print(sols)
[[1, 1, 1, 1, 1, 1], [1, 5], [5, 1]]
您可以嘗試將總列表添加到 function 並在 n - c 小於 0 或for loop for c in coins:
def possible_change(n,p=[],coins = [1,5,10], total=[]):
if n == 0:
total.append(p)
else:
for c in coins:
if n - c >= 0:
print("c {}".format(c))
possible_change(n-c,p+[c],coins=coins)
else:
return total
return total
print(possible_change(6,coins=[1,5,10]))
結果
[[1, 1, 1, 1, 1, 1], [1, 5], [5, 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.