(算法)硬币问题

问题:有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);
    }
}
相关推荐
地平线开发者8 小时前
profiler debug 工具用法与高一致性策略
算法·自动驾驶
编程大师哥8 小时前
匿名函数 lambda + 高阶函数
java·python·算法
我叫袁小陌8 小时前
算法解题思路指南
算法
地平线开发者8 小时前
Conv+BN+Add+ReLU 融合机制简介
算法·自动驾驶
yuanyuan2o28 小时前
模型预训练:Hugging Face Transformers 基础
算法·ai·语言模型·自然语言处理·nlp·深度优先
杨充9 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
妄想出头的工业炼药师9 小时前
GS slam mono
算法·开源
_日拱一卒10 小时前
LeetCode:207课程表
java·数据结构·算法·leetcode·职场和发展
用户9874092388712 小时前
llamafactory 0.6.3 没有 llamafactory-cli
算法