use*_*217 2 python recursion dynamic-programming np
我很难理解下面的代码.它用可用面额的硬币('硬币')计算赚钱金额('n')的方法数量
def change(n, coins_available, coins_so_far):
if sum(coins_so_far) == n:
yield coins_so_far
elif sum(coins_so_far) > n:
pass
elif coins_available == []:
pass
else:
for c in change(n, coins_available[:], coins_so_far+[coins_available[0]]):
yield c
for c in change(n, coins_available[1:], coins_so_far):
yield c
n = 15
coins = [1, 5, 10, 25]
solutions = [s for s in change(n, coins, [])]
for s in solutions:
print s
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5]
[1, 1, 1, 1, 1, 5, 5]
[1, 1, 1, 1, 1, 10]
[5, 5, 5]
[5, 10]
Run Code Online (Sandbox Code Playgroud)
我理解第一次迭代是如何导致[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]我不明白[1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1]转换为[1,1,1,1,1,1,1,1,1,1] 1,5]我相信'coins_so_far'在第二次迭代时仍将保持[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] coins_available'持有[5,10,25]
任何帮助是极大的赞赏.谢谢
用英语讲:
How to determine the ways to make change(for n cents, using coins in
coins_available denominations, and which include a pile of coins_so_far):
If the coins_so_far sum to n:
That is the unique way to do it.
(Because we've already added enough coins to the pile to make
the desired amount of change.)
Otherwise, if the coins_so_far sum to more than n:
There are no ways to do it.
(Because there's already too much in our pile; we can't fix
this by adding more.)
Otherwise, if there are no coins_available:
There are no ways to do it.
Otherwise:
(To make change for the rest of the pile, we either *do* add
at least one more of the smallest possible coin, or we *don't*.)
Every way to make change(for n cents, using the same
coins_available, and which includes the coins_so_far
as well as the first of the coins_available):
Is one of the ways to do it.
(Try adding a coin of the smallest denomination to the pile,
and then figure out all the ways to make up the rest of the
change. This finds the ways that do add the small coin.)
Every way to make change(for n cents, using all the
coins_available except the first, and including the
coins_so_far):
Is also a way to do it.
(Find the ways that don't add the smallest coin denomination,
by excluding it from the denominations we'll consider, and
using the same process.)
Run Code Online (Sandbox Code Playgroud)