给定目标金额和硬币面额列表,我的代码应该找到达到目标金额所需的最少硬币。
例子:
C(78, [1, 5, 10, 25, 50]) = 6
- 我们可以从 3x 25+ 3x得到 78 1,所以需要 6 个硬币
C(48, [1, 7, 24, 42]) = 2
- 48 = 2x 24,所以 2 个硬币就足够了
C(35, [1, 3, 16, 30, 50]) = 3
- 我们可以从 2x 16+ 1x得到 35 3,所以 3 个硬币就足够了
我用 for 循环编写了代码,但是如何让它递归呢?
def C(i, coins, cdict = None):
if cdict == None:
cdict = {}
if i <= 0:
cdict[i] = 0
return cdict[i]
elif i in cdict:
return cdict[i]
elif i in coins:
cdict[i] = 1
return cdict[i]
else:
min = 0
for cj in coins:
result = C(i - cj, coins)
if result != 0:
if min == 0 or (result + 1) < min:
min = 1 + result
cdict[i] = min
return cdict[i]