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