Coin Change 换零钱的方法

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3
return -1.

Note:

You may assume that you have an infinite number of each kind of coin.

这是一个道可以用动态规划的思想来做的题目。在这里会介绍2种方法,一种是递归的,这种很直观,我一开始也是采用这个方法,另一种是迭代的。

目的是要选择最小的组合数。这其实和找出Sum符合要求的组合 非常的类似。

唯一的差别在于:前者要找所有可能的组合,这里要求找出最小个数的组合。

我们来考虑Example 1。 为了找amount = 11,

如果我已经有了组成 amount[10], amount[9], amount[6]的最小的个数。

因为所以,如果amount[10], amount[9], amount[6] 都为- 1的话,那么amount[11]也只能是-1了。

不全为-1的话,amount[11]为不为-1中的最小值 + 1。(+1是因为本身选择了一个coin)

运行时间:


代码:

    public int coinChange(int[] coins, int amount) {
        int[] cache = new int[amount + 1];//store the min number of coins of certain amount
        for (int i = 0; i < cache.length; i++) {
            cache[i] = Integer.MIN_VALUE;
        }
        cache[0] = 0;
        return doCoinChange(coins, cache, amount);
    }

    private int doCoinChange(int[] coins, int[] cache, int amount) {
        if (amount < 0) {
            return -1;
        }
        if (cache[amount] != Integer.MIN_VALUE) {
            return cache[amount];
        }
        int curMin = Integer.MAX_VALUE;
        for (int i = coins.length - 1; i >= 0; i--) {
            int curResult = doCoinChange(coins, cache, amount - coins[i]);
            if (curResult != -1) {
                curMin = Math.min(curMin, curResult);
            }
        }
        cache[amount] = curMin == Integer.MAX_VALUE ? -1 : curMin + 1;// add this number
        return cache[amount];
    }

下面介绍基于迭代的想法。这是一种bottom-up思想的。

思想就是:假设我已经有了和 <=amount 的所有最小个数。那么amount + 1是多少呢?

运行时间:


代码:

    public int coinChange2(int[] coins, int amount) {
        if (amount < 1) {
            return 0;
        }
        int[] cache = new int[amount + 1];
        int sum = 0;
        while (++sum <= amount) {
            int min = -1;
            for (int coin : coins) {
                if (sum >= coin && cache[sum - coin] != -1) {
                    int temp = cache[sum - coin] + 1;
                    min = min < 0 ? temp : (temp < min ? temp : min);
                }
            }
            cache[sum] = min;
        }
        return cache[amount];
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值