(算法)硬币问题

问题:有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);
    }
}
相关推荐
小L~~~4 小时前
基于贪心策略的混合遗传算法求解01背包问题
python·算法
洛水水4 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
jieyucx4 小时前
Go 语言 sort 包详解:从基础排序到自定义排序(含底层原理+零基础看懂)
算法·golang·排序算法·sort
叁散6 小时前
ESP32 LCD1602显示实验报告
算法
过期动态6 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒6 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
君为先-bey6 小时前
LeMiCa——基于扩散模型的高效视频生成的词典序最小化路径缓存
python·算法·机器学习·扩散模型
洛水水6 小时前
【力扣100题】58.轮转数组
算法·leetcode
资深流水灯工程师6 小时前
LMS 最小均方算法在 DSP 上的 C 语言实现
算法
风筝在晴天搁浅6 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表