[Leetcode]--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.

分析

       这是一道典型的动态规划类型的题目。我们设number为存储组成指定amount值所需硬币数的数组。显然,当number[0]=0(需要0枚硬币组成价值0)。则组成指定amount所需硬币数number[amount]=min(number[amount], number[amount-coins[i]]+1),其中coins[i]为小于amount的硬币面值。对于每一个小于amount的硬币面值,amount可以由组成面值amount-coins[i]所需的最小数目加1得到,其与当前number[amount]比较,选择较小的,即为最终结果。
       注意,为了判断无法组成指定amount的情况,我们将number数组除number[0]外设置为大于amount的值,这样,若最终number[amount]>amount,则判断无法用给定硬币面值组成amount值。

解答

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int n=amount+1;
        int length=coins.size();
        vector<int> number(n,n);
        number[0]=0;
        for(int i=1;i<n;i++){
            for(int j=0;j<length;j++){
                if(coins[j]<=i){
                    number[i]=min(number[i],number[i-coins[j]]+1);
                }
            }
        }
        if(number[amount]>amount)
            return -1;
        else return number[amount];
    }
};
        时间复杂度为O(amount*length),其中length为coins数组长度。

猜你喜欢

转载自blog.csdn.net/weixin_38057349/article/details/79103542