动态规划 之 金币找零

该博客介绍了一个使用动态规划算法解决找零问题的Java实现,具体为找到用最少数量的特定面额金币来凑足给定金额。算法通过递归方式计算,并使用HashMap缓存中间结果以优化效率。读者可以输入不同的找零数额,程序会输出相应的找零方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细链接: https://github.com/buWenCangS/jsLearn/blob/master/%E7%AE%97%E6%B3%95/%E7%AE%97%E6%B3%95%E8%AE%BE%E8%AE%A1%E5%92%8C%E6%8A%80%E5%B7%A7.md

```

public class ChangeMoney {

    
    public static HashMap<Integer, ArrayList<Integer>> cache= new HashMap<Integer, ArrayList<Integer>>();
    public static void main(String[] args) {
        int[] moneys = new int[]{1,2,5,10};
        changeMoney(63,moneys);
        while(true){
            
            System.out.println("输入你想查找的找零数额:");
            Scanner scan = new Scanner(System.in);
            int totalMoney = scan.nextInt();
            if(totalMoney == 0){
                System.out.println("退出程序...");
                break;
            }
//            printList();
            System.out.println(changeMoney(totalMoney, moneys).toString());
        }
    }
    
    public static ArrayList<Integer> changeMoney(int totalMoney , int[] moneys){
        if(totalMoney == 0){
            return new ArrayList<Integer>();
        }
        
        if(cache.get(totalMoney) != null){ // 返回已存在的缓存数据
            return cache.get(totalMoney);
        }
        
        ArrayList<Integer> min = null;
        ArrayList<Integer> newMin = null;
        ArrayList<Integer> list = null;
        int money = totalMoney;
        
        for (int i = 0; i < moneys.length; i++) {
            money = totalMoney - moneys[i];
            if(money >= 0){
                newMin = changeMoney(money, moneys);
            }
            
            /*
             * 判断是不是最小的找零数组, 如果是就将数据添加到最小找零列表中
             */
            if(money >= 0 && (min == null || newMin.size() < min.size() - 1)){
                list = new ArrayList<Integer>();
                list.add(moneys[i]);
                list.addAll(newMin);
                System.out.println("对总数 : " + totalMoney + "  进行找零");
//                printList(list);
                System.out.println(list.toString());
                min = list;
                cache.put(totalMoney, min);
            }
        }
        
        return cache.get(totalMoney);
    }
    
    public static void printList(ArrayList<Integer> list){
        
        for (Integer i : list) {
            System.out.print(i + "    ," );
        }
        System.out.println();
    }
}

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值