码迷,mamicode.com
首页 > 其他好文 > 详细

Coin Change

时间:2018-07-07 12:36:14      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:exp   any   hat   class   ons   Plan   tput   money   ret   

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.

class Solution {
    public int coinChange(int[] coins, int amount) {
        int max = amount+1;
        int[] a = new int[max];
        Arrays.fill(a,1,max,max);
        for (int i = 1; i < max; i++) {
            for (int j = 0; j < coins.length; j++) {
                if (i>=coins[j] && a[i-coins[j]] + 1 < a[i]) {
                    a[i] = a[i-coins[j]] + 1;
                }
            }
        }
        return a[amount] == max ? -1 : a[amount];
    }
}

 

Coin Change

标签:exp   any   hat   class   ons   Plan   tput   money   ret   

原文地址:https://www.cnblogs.com/liudebo/p/9276800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!