(算法)硬币问题

问题:有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);
    }
}
相关推荐
老师我太想进步了20262 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志783242 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU1142 小时前
P1481 魔族密码
c++·算法·动态规划
加宝的起点雷达6 小时前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业
秋天的怀念_David6 小时前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
闻缺陷则喜何志丹8 小时前
【C++特性】四种类型转
c++·算法·类型转换
喵本喵叁肆9 小时前
用 Boosting 把弱隐私算法炼成强隐私算法(英文原题:Boosting and Differential Privacy (FOCS 2010))
算法·集成学习·boosting
青梅味猪大肠9 小时前
【操作系统-60】临近适应算法
java·linux·开发语言·嵌入式硬件·算法·操作系统