Currency exchange problem solving dynamic programming method #
There are n # currency coin denominations of v1, v2, v3 ... vn, where v1 = 1, the use of money with a total value of money exchange, how to find the minimum number of coins, i.e., x1, x2, x3 ... xn minimum sum
# Input: nominal value of various currencies v1, v2, v3 ... vn; To redeem the total value of money
# Output: get the least amount of currency exchange
1 # Denomination modified money system 2 V = [1,2,5,10,50 ] . 3 # amount of money to be modified exchange Money . 4 Money = 253
1 # initial amount of money for each of 0 2 X = [0] * len (V) . 3 # establishing a corresponding number of currency exchange table = Q [Money + 1] [len (V) + 1'd] . 4 Q = [([0 ] * (len (V) + 1'd)) for I in Range (0, + Money. 1 )]
. 1 # Q Table Initialization: The first row of the first column is set 0 2 for I in Range (0, + Money. 1 ): . 3 Q [I] [0] = 0 . 4 for I in Range (0, len (V) + 1'd ): . 5 Q [0] [I] = 0
1 # sheet process 2 for I in Range (1, Money + 1 ): . 3 for J in Range (1, len (V) + 1'd ): . 4 IF V [J-1] == I: # denomination = i . 5 Q [I] [J] =. 1 . 6 elif V [J-. 1]> I: # denomination> I . 7 Q [I] [J] = Q [I] [J-. 1 ] . 8 the else : # denomination <i . 9 Q [i] [J] = Q [IV [-J. 1]] [J] +. 1 # IV [J] is the nominal value of i
Function call:
. 1 Print (Q); Print ( ' \ n- ' ) 2 Print ( ' exchange to give a minimum number of currencies: ' , Q [Money] [len (V)])
operation result:
A number obtained at least for currency conversion: 7