コインチェンジ問題をやっています。最小限の変更を可能にするために必要なコインの数を出力するという問題は終了しましたが、それらのコインも出力するようにプログラムを変更するにはどうすればよいですか??
サンプル I/O は次のとおりです。
input: coin_change(48, [1, 5, 10, 25, 50])
output: [6, [25, 10, 10, 1, 1, 1]]
input: coin_change(48, [1, 7, 24, 42])
output: [2, [24, 24]]
現在、私のコードは 6 のみを返します。
ちなみに、これは再帰のみで行う必要があります。ループは許可されません。
コード:
def change(C, V):
def min_coins(i, aC):
if aC == 0:
return 0
elif i == -1 or aC < 0:
return float('inf')
else:
return min(min_coins(i-1, aC), 1 + min_coins(i, aC-V[i]))
return min_coins(len(V)-1, C)
以下のコードは私が試したものですが、2番目の入力では機能しません
def giveChange(C, V, res = None):
res=[] if res is None else res
if len(V)==0:
return len(res),res
maxx=max(V)
print maxx
V.remove(maxx)
ans=C//maxx
if ans==0 and maxx<C :
print maxx
res +=[maxx]*ans
return len(res),res
else:
res += [maxx]*ans
return giveChange(C % maxx,V,res)