The problem of dynamic programming has been studied recently. Today I have a problem with the coin pick.
In fact, dynamic planning or, I go from the bottom to the top, in turn, to find the minimum value of each state, and then can be labeled on.
The problem is, if there are 1,5,7,10 these four kinds of currency coins, I take 14 yuan, the minimum number of coins to take.
In fact, dynamic programming is to ask for a state transfer equation, like my last blog to find the shortest path problem. And this is a coin problem. If my coin is greater than the value of the currency, then the state can be transferred
Transfer to TEMP[I-WEIZHI[J] + 1. Temp[] is the minimum number used to hold each currency. Weizhi[] is used to store currency. For example, temp[0] means to take 0 currency 0 times, temp[1] 1 is more than 1, so can take 1 coins. Then convert into temp[1-1]+1, take 1 times
TEMP[2], 2 is only more than 1, then converted into temp[2-1]+1 ... to temp[5] is not the same, temp[5] 5 is greater than 1, so you can take temp[5-1]+1 = 5, but also can take temp[5-5]+1 = temp[0] +1 = 0+1 = 1. It is entirely possible to make up the code with this idea. But here is a problem, I need to compare my smallest one, this time directly with the variable to store it, do not habitually want to use the array, I started just want to use the array, but also crossed the line, the following is my code, in fact, that for loop is the core of dynamic planning. It can be understood as filling in numbers. It's so late today, let's update the code to fill in the numbers tomorrow.
Import Java.util.scanner;public class Find change {public static void main (string[] args) {Scanner SCN = new Scanner (system.in); System.out.println ("Please enter how many coins you want to calculate:"); int n = scn.nextint (); int temp[] = new int[n+1]; The minimum number of ways to store each coin is int weizhi[] = {1,5,7,10}; The core of four coins//dynamic programming, with a for loop to fill the number of tokens on each can (int i=1;i<temp.length;i++) {//Take the amount of coins int minv = i;//Initialize the smallest of the MINV, Because the minimum number of coins will certainly not be greater than I also for (int j=0;j<weizhi.length;j++) {if (I>=weizhi[j]) {//Take the number of coins larger than the number. int k = Temp[i-weizhi[j]] + 1; The state transition equation, described earlier. if (K<MINV) {minv = k; Saved, this trip compares the smallest taken coin value}}}temp[i] = MINV;} SYSTEM.OUT.PRINTLN ("Need at least" + temp[n] + "coin");}}
Java dynamic planning to take coin problem