這是動態編程的一個例子
,您可以對動態編程標準公式實現它(見Coin Change Problem)
讓s = {1,5,10,25}
我們coinset現在是標準的硬幣面值
讓f(x,y) = number_of_ways_to_make_change
讓x=change_due;y=allowed_coinset_index
- 備註:如果y == 0,我們允許的coinset是{1},如果y == 1,我們允許的coinset是{1,5} ...
- 任何change_due有1一個簡單的解決方案時,我們coinset只由{1}也就是說,如果你只有幾分錢,只存在一個方法,使改變(所有便士)
- ERGO
f(anything,0) == 1 && f(0,anything) == 1 && f(anything,anthing < 0) == 0
讓我們解決了幾個change_due值
change_due function_call
1 f(1,0) = 1
...
4 f(4,0) = 1
5 f(5,1) = f((5-5),1) + f(5,0) = 1 + 1 = 2
...
9 f(9,1) = f(9-5,1)+f(9,0) = f(4,1) + 1 = f(4,0*) + 1 = 1+1 = 2
10 f(10,2) = f(10-10,2) + f(10,1) = f(0,2) + (f(5,1)+f(10,0))= 1+(2+1) = 4
,所以我們可以看到我們的基地情況
f(x,0) = f(0,y) = 1
f(x is less than zero,y) = f(x,y is less than zero) = 0
注意,這適用於任何一組硬幣
V 的,這是重要的組成部分 V
#if x,y are not in above conditions we want to recursively call ourselves allowing us to build up to a complex solution from several simpler solutions
f(x,y) = f(x-CHANGE_DENOM,y) + f(x,y-1)
可以從上面保持與該表玩,看看我們有多少種方法可以使16美分
S = [1,5,10,25]
# our y is 2 (since S[2] = 10 which is the largest denomination < our change_due(16))
f(16,2) = f(16-S[2],2) + f(16,1)
= f(16-10,2) + f(16,1) = f(6,2) + f(16,1)
f(6,2) = f(6-S[2]) + f(6,1) = 0 + f(6,1) = 0+2#(see below) =
f(16,1) = f(16-S[1],1) + f(16,0) = f(11,1) + 1
f(11,1) = f(11-S[1],1) + f(11,0) = f(6,1) + 1
f(6,1) = f(6-S[1],1) + f(6,0) = f(1,1) + 1
f(1,1) = f(1-S[1],1) + f(1,0) = 0 + 1 = 1
f(6,1) = f(1,1) + 1 = 1 + 1 = 2
f(11,1) = f(6,1) + 1 = 2 + 1 = 3
f(16,1) = f(11,1) + 1 = 3+1 = 4
f(16,2) = f(6,2) + f(16,1) = 2 + 4 = 6 ways to make change for 16 cents
現在你只需要讓你的大coinset工作
哪裏是你的CURREN t代碼?什麼意思是「不起作用」:錯誤(提供完整的追溯),意想不到的輸出(提供輸入和預期的和實際的輸出)? – jonrsharpe
這是一個功課題嗎?如果是這樣,請顯示你的努力到目前爲止。 – nish
我有點受騙...我打開這個問題,期待看看「2 python的力量」是什麼。至少, –