Algorithm Description:
A dynamic planning algorithm is usually used to solve a problem with an optimal nature. In such problems, there may be many feasible solutions. Each solution corresponds to a value. We hope to find a solution with the optimal value. The basic idea is to break down the problem to be solved into several subproblems. First, solve the subproblems, save the results of the subproblems, and then obtain the original solutions from the subproblems. Dynamic Planning is essentially a technology that uses space for time. in the implementation process, it has to store various states in the Process of generation. Therefore, its spatial complexity is greater than that of other algorithms.
Problem description:
There are now a bunch of nominal values V1, V2, V3... Number of coins per unit. How many coins are needed to find the change with a total value of T units?
Solution:
1. Find the coin V www.2cto.com whose face value is closest to T.
2, f (T) problem is converted into f (T-V) + 1 problem, in order to appear Recursion
Code implementation:
The CoinChange class is used to handle coin-seeking businesses:
[Java]
Public class CoinChange {
/**
* Get the number of coins to be changed to zero
* @ Param coinValue the nominal value of the coin
* @ Param totalValue The amount of money to be zero
* @ Return
*/
Public int coinNum (int [] coinValue, int totalValue ){
List <Integer> coins = new ArrayList <Integer> ();
Coins. add (0 );
For (int I = 1; I <= totalValue; I ++ ){
Int coin = nearestCoin (I, coinValue );
Int coinNum = coins. get (I-coin) + 1;
Coins. add (coinNum );
}
Return coins. get (totalValue );
}
/**
* Obtain the coin face value that is closest to the value of the nearest 0.
*/
Private int nearestCoin (int value, int [] coinValues ){
Int res = 0;
Int nearest = Integer. MAX_VALUE;
For (int coinValue: coinValues ){
If (coinValue <= value ){
Int distance = value-coinValue;
If (distance <nearest ){
Nearest = distance;
Res = coinValue;
}
}
}
Return res;
}
}
The Main class is used for testing:
[Java]
Public class Main {
Public static void main (String [] args ){
CoinChange coinChange = new CoinChange ();
Int res = coinChange. coinNum (new int [] {1, 2, 3, 5, 11}, 81 );
System. out. println (res );
}
}
Print Output: 9