(算法)硬币问题

问题:有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);
    }
}
相关推荐
样例过了就是过了2 分钟前
LeetCode热题100 电话号码的字母组合
数据结构·c++·算法·leetcode·dfs
nervermore9903 分钟前
1.10 面试经典150题-多数元素
算法
c++逐梦人3 分钟前
二分查找模版及二分答案例题
算法·蓝桥杯
biubiuibiu12 分钟前
选择适合的硬盘:固态与机械硬盘的对比与推荐
c++·算法
big_rabbit050216 分钟前
[算法][力扣226]翻转一颗二叉树
数据结构·算法·leetcode
TracyCoder12320 分钟前
LeetCode Hot100(65/100)——64. 最小路径和
算法·leetcode·职场和发展
z2014z21 分钟前
Deflate 算法详解
网络·算法
条tiao条21 分钟前
从 “Top-K 问题” 入门二叉堆:C 语言从零实现与经典应用
c语言·算法·深度优先
uesowys23 分钟前
华为OD算法开发指导-数据结构-图
数据结构·算法·华为od
实心儿儿27 分钟前
算法3:链表分割
数据结构·算法·链表