当前位置:网站首页>Li Kou: Change

Li Kou: Change

2022-06-21 22:24:00 Sunset_ hd99

Give you an array of integers coins , Coins of different denominations ; And an integer amount , Represents the total amount .

Calculate and return the amount needed to make up the total amount The minimum number of coins . If no combination of coins can make up the total amount , return -1 .

You can think of the number of coins of each kind as infinite .

Example  1:

 Input :coins = [1, 2, 5], amount = 11
 Output :3 
 explain :11 = 5 + 5 + 1
class Solution {
    public int coinChange(int[] coins, int amount) {
        int[] f = new int[amount+1];
        int n = coins.length;
        f[0] = 0;
        
        for(int i = 1; i <= amount; ++i){
            f[i] = Integer.MAX_VALUE;
            for(int j = 0 ; j < n; ++j){
                if(i >= coins[j] && f[i - coins[j]] != Integer.MAX_VALUE){
                    f[i] = Math.min(f[i - coins[j]] + 1 , f[i]);
                }
            }
        }

        if(f[amount] == Integer.MAX_VALUE){
            f[amount] = -1;
        }
        return f[amount];

    }
}

原网站

版权声明
本文为[Sunset_ hd99]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206212031448605.html