(算法)硬币问题

问题:有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 分钟前
大模型蒸馏
人工智能·算法·数据挖掘·大模型
Benny_Tang6 分钟前
P9527 [JOIST 2022] 洒水器 / Sprinkler 题解
c++·算法
kiracrimson30 分钟前
希尔排序:让插入排序不再怕逆序
数据结构·算法·排序算法
yi0111 小时前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
陈希瑞1 小时前
LongCat-2.5-Preview 的web逆向能力实测
人工智能·算法·wasm
tangguofeng3 小时前
基于分治策略的循环赛日程表问题的思路讲解
算法
起个名字费劲死了3 小时前
VisionMaster集成深度学习算法(基础狗)
人工智能·深度学习·算法
lengxuenong3 小时前
枚举例题分析
c++·算法·青少年编程
Navigator_Z4 小时前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
2601_965742224 小时前
短视频脚本创作方法分享:本地生活类账号的起步思路
大数据·人工智能·算法·ai·新媒体运营·生活