322. Coin Change

栏目: Java · 发布时间: 5年前

内容简介: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, retur

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];
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

C标准库

C标准库

P. J. Plauger / 卢红星、徐明亮、霍建同 / 人民邮电出版社 / 2009-7 / 79.00元

本书是由世界级C语言专家编写的C标准库经典著作。英文版已经重印十多次,影响了几代程序员。 本书结合C标准的相关部分,精辟地讲述了每一个库函数的使用方法和实现细节,而这正是一个真正的C程序员所必须掌握的。更重要的是,书中给出了实现和测试这些函数的完整源代码,可以让你更深入地学习C语言。不仅如此,本书还讨论了一些即使是最有经验的C程序员通常也不熟悉的知识,比如国际化和独立于区域设置的程序的编写、......一起来看看 《C标准库》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试