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 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:
Public class coinchange {/*** get the number of coins to be changed * @ Param coinvalue the coin's face value * @ Param totalvalue The amount of money to be changed * @ 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);}/*** get the coin face value closest to the value of the change */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:
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