(算法)硬币问题

问题:有1元,5元,10元,50元,100元,500元的硬币各有C1,C5,C10.C50,C100,C500个。

           现在要用这些硬币来支付A元,最小需要多少枚硬币?

该题使用递归算法,利用局部最优解来推导全局最优解。

import java.util.Scanner;

import static java.lang.Math.min;

public class coin {
    static int[] cnts=new int[6];
    static int[] coins={1,5,10,50,100,500}; //硬币面额大小
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输出每个硬币的个数");
        for (int i = 0; i < 6; i++) {       //输出每个硬币各有多少个
            cnts[i]=sc.nextInt();
        }
        System.out.println("请输出总金额");
        int A=sc.nextInt();             //输出金额
        int res=f(A,5);         //最开始由最大硬币面额500开始
        System.out.println(res);
    }
    static int f(int A,int cur)
    {
        if(A<=0)return 0;
        if(cur==0)return A;
        int coinValue=coins[cur];
        int x=A/coinValue;          //该金额有多少个
        int cnt=cnts[cur];
        int t=min(x,cnt);       //
        return t+f(A-t*coinValue,cur-1);
    }
}

相关推荐

  1. (算法)硬币问题

    2024-07-14 06:14:01       25 阅读
  2. 最少硬币问题

    2024-07-14 06:14:01       45 阅读
  3. 算法】排硬币

    2024-07-14 06:14:01       36 阅读
  4. B3635 硬币问题 洛谷 源代码

    2024-07-14 06:14:01       16 阅读
  5. Ubuntu系统和硬件问题

    2024-07-14 06:14:01       25 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-14 06:14:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-14 06:14:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-14 06:14:01       58 阅读
  4. Python语言-面向对象

    2024-07-14 06:14:01       69 阅读

热门阅读

  1. 【代码复现】STAEformer

    2024-07-14 06:14:01       21 阅读
  2. python中的pickle模块和json模块

    2024-07-14 06:14:01       23 阅读
  3. ClickHouse实战第二章-ClickHouse 的安装调试

    2024-07-14 06:14:01       25 阅读
  4. Spring事件监听机制详解

    2024-07-14 06:14:01       22 阅读
  5. 案例:分库分表与SELECT * 发生的线上问题

    2024-07-14 06:14:01       24 阅读
  6. TypeScript的类型谓词与控制流分析

    2024-07-14 06:14:01       26 阅读
  7. ThreadLocal详解

    2024-07-14 06:14:01       22 阅读
  8. 小程序如何刷新当前页面

    2024-07-14 06:14:01       25 阅读
  9. qt 根据名称获取按钮,并添加点击事件

    2024-07-14 06:14:01       19 阅读
  10. Linux开发讲课37--- ARM的22个常用概念

    2024-07-14 06:14:01       27 阅读