Problem description:
For coins with a nominal value of 2 cents, 5 cents, 1 cent, 5 cents, and 1 cent respectively, please provide the best solution for finding n cents (requires the minimum number of coins to be found)
Problem Analysis:
According to common sense, when we go to the store to buy things and find money, the boss always gives us the largest face value first. If it is not enough, we will find a smaller face value until it is full. If the boss gives you a score or a few cents, you must not do it. In addition, he may not have that much money to find. In fact, this is a typical greedy choice problem.
Problem algorithm design and implementation:
For example, if the boss wants to give me 99 cents, he has the number of coins with the nominal values of 25, 10, and 5 respectively. In order to find the minimum number of coins, so should he look for it like this? First, let's look at the number of 25 points he should look for. Ah 99/25 = 3, it seems to be 3. If it is 4, we have to give the boss another one. I don't want to do it, so the boss can only give me three 25 points, because it still gives me less than 24, so I have to give me two 10 points and four 1 points.
Implementation
// Change search algorithm <br/> // input: array M, which stores the number of nominal values in ascending order, and N is the amount of money to be searched, unit: All Points <br/> // output: array num, the number of coins with different face values in the array M, find the money solution <br/> Public static int [] Zhaoqian (int m [], int N) <br/>{< br/> int K = m. length; <br/> int [] num = new int [k]; <br/> for (INT I = 0; I <K; I ++) <br/>{< br/> num <I> = N/m <I>; <br/> N = n % m <I>; <br/>}< br/> return num; <br/>}< br/>
Public class Zhaoqian <br/>{< br/> Public static void main (string [] ARGs) <br/>{< br/> int M [] = {25, 10, 5, 1 }; <br/> int n = 99; <br/> int [] num = new int [M. length]; <br/> num = Zhaoqian (m, n); <br/> system. out. println (n + "the money-seeking solution:"); <br/> for (INT I = 0; I <m. length; I ++) <br/> system. out. println (Num <I> + "Mei" + M <I> + "par "); <br/>}< br/> Public static int [] Zhaoqian (int m [], int N) <br/>{< br/> int K = m. length; <br/> int [] num = new int [k]; <br/> for (INT I = 0; I <K; I ++) <br/>{< br/> num <I> = N/m <I>; <br/> N = n % m <I>; <br/>}< br/> return num; <br/>}< br/>