322. 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:

Input: coins = [1, 2, 5], amount = 11
Output: 3 
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Note:

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

难度:medium

题目:给定不同面值的硬币和一总金额。写一个函数来计算你需要的最少的硬币数量来构成这个总金额。如果这笔钱不能用硬币的任何组合来构成,则返回-1。

思路:DP

total[i]表示这个金额最少需要多少硬币组成。

total[amount] = Math.min(total[amount – coins[i]] + 1) (total[amount – coins[i]] > 0)

(total[amount – coins[i]] = 0) 意味着不可达。

Runtime: 13 ms, faster than 97.29% of Java online submissions for Coin Change.

Memory Usage: 38 MB, less than 42.39% of Java online submissions for Coin Change.

class Solution {
    public int coinChange(int[] coins, int amount) {
        if (null == coins || coins.length < 1 || amount <= 0) {
            return 0;
        }
        int[] total = new int[amount + 1];
        Arrays.sort(coins);
        for (int i = 0; i < coins.length && coins[i] < total.length; i++) {
            total[coins[i]] = 1;
        }
        
        for (int i = coins[0]; i <= amount; i++) {
            if (total[i] > 0) {
                continue;
            }
            total[i] = amount + 1;
            for (int j = 0; j < coins.length && i - coins[j] >= 0; j++) {
                if (total[i - coins[j]] > 0) {
                    total[i] = Math.min(total[i - coins[j]] + 1, total[i]);
                }
            }
        }
        
        return total[amount] > amount || total[amount] <= 0 ? -1 : total[amount];
    }
}

原文 

https://segmentfault.com/a/1190000018386573

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 322. Coin Change

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址