DFS的灵活应用二:零钱兑换

2 篇文章 0 订阅
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1

示例:
输入: coins = [1, 2, 5], amount = 11
输出: 3 
解释: 11 = 5 + 5 + 1

思路:数组整体降序排列,然后dfs深度遍历,每次都挑额度大的先拿,以目前金额能拿多少就拿多少,拿多了就回溯走其他情况,相当于要把全部情况走一遍找到最小次数

代码设计中比较好的点:

  • 有的回溯是要在递归的后面做额外补偿,此处的回溯是基于当前情况的for循环遍历
  • 剪枝逻辑(当前硬币金额拿的个数+历史已拿个数<目前已知最少次数),相当于避免了很多无用递归执行

代码如下:

public class Solution {

    class Times {

        public Times(int bestTimes) {
            this.bestTimes = bestTimes;
        }

        private int bestTimes;


        public int getBestTimes() {
            return bestTimes;
        }

        private void compareMin(int num) {
            if(num < bestTimes) {
                bestTimes = num;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1,2,5};
        Solution solution = new Solution();
        int count = solution.coinChange(arr, 11);
        System.out.println(count);
    }


    public int coinChange(int[] coins, int amount) {
        Integer[] arr = Arrays.stream(coins).boxed().toArray(Integer[]::new);
        Arrays.sort(arr, Collections.reverseOrder());
        Times times = new Times(Integer.MAX_VALUE);
        dfsFind(arr, amount, 0, 0, times);
        return times.getBestTimes() == Integer.MAX_VALUE ? -1 : times.getBestTimes();
    }

    public void dfsFind(Integer[] coins, int amount, int index, int count, Times times) {
        if(amount == 0) {
            times.compareMin(count);
            return;
        }
        if(index == coins.length) {
            return;
        }

        for(int k=amount/coins[index]; k>=0 && k+count<times.getBestTimes(); k--) {
            dfsFind(coins, amount-k*coins[index], index+1, k+count, times);
        }

    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值