8.2贪心策略简介及硬币支付问题

硬币问题
有1元,5元,10元,50元,100元,500元的硬币各c1,c5,c10,c50,c100,c500枚.
现在要用这些硬币来支付A元,最少需要多少枚硬币?
假定本题至少存在一种支付方案.

0≤ci≤10^9

0≤A≤10^9

输入:
第一行有六个数字,分别代表从小到大6种面值的硬币的个数
第二行为A,代表需支付的A元

样例:
输入
3 2 1 3 0 2
620

输出
6
说明:1500+250+110+25,共6枚

思路:
看眼前最优,每次递归总数减去最大面值的硬币数量*最大面值,最大面值下标更新。

 1 import java.util.Scanner;
 2 
 3 public class Eight_2贪心策略简介及硬币支付问题 {
 4     static int[] cnts = new int[6];
 5     static int[] coins = {1,5,10,50,100,500};
 6 
 7     public static void main(String[] args) {
 8         Scanner in = new Scanner(System.in);
 9         
10         for(int i = 0; i < 6; i++){
11             cnts[i] = in.nextInt();
12         }
13         int A = in.nextInt();
14         int res = f(A, 5);
15         System.out.println(res);
16     }
17 
18     /**
19      * 尽量先用大面值,因为不用大面值的而使用更多小面值的话,一定得不到最优解
20      * coins 提供的面值
21      * cnts 手上已有面值的硬币数量
22      * A 支付总数
23      * cur 先指向最大面值的硬币
24      */
25     private static int f(int A, int cur) {
26         if(A <= 0)
27             return 0;
28         if(cur == 0)
29             return A;
30         
31         int coinValue = coins[cur];
32         int x = A/coinValue; //金额有多少个coinValue
33         int cnt = cnts[cur]; //当前面值的硬币有cnt个
34         int t = Math.min(x, cnt);
35         return t + f(A-t*coinValue, cur-1);
36         
37     }
38 }

猜你喜欢

转载自www.cnblogs.com/z1110/p/12704507.html