322. Coin Change

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

Functional Interface:
int coinChange(vector<int>& coins, int amount)

已知我們有n種面額的錢幣,從小到大依次存入coin中,之後我們一共要湊夠amount的金額,並且要使總錢幣的個數最小;若是不存在,則返回-1。

這道題實際上是一道動態規劃的找零問題。我們想求總金額爲amount的最小錢幣數,也就是要求amount-小於amount的最大面額的最小錢幣數。所以我們可以從最小金額(1,對於0來說,最小錢幣數永遠是0)開始求解最小錢幣數,通過循環,依次求解金額(i)爲1~amount的最小錢幣數。對於每一個金額,我們都有

result[i]=min(result[i],result[icoins[j]]+1)
其中i是金額,j是指第j種面額,result是存儲各個金額的最小錢幣數。

對於不存在在的情況,我們則將其設爲一個很大的值(infinity)。由上述公式可知,若是某種金額不存在找零的情況,那麼其result[i-coins[j]]必然會是infinite,因爲它也不存在找零情況。也就是說,所有不存在找零的金額,它對應的result中存儲的值一定爲infinity,那麼必然有當當我們求解完amount的最小錢幣數時,若是爲infinity,則意味着改金額不存在找零的情況,返回-1,其餘情況則返回求得的最小錢幣數。

參考代碼如下:

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int infinity = 2*amount;
        vector<int> result(amount+1, infinity);
        result[0] = 0;
        for(int i = 1; i <= amount; i++) {
            for(int j = 0; j < coins.size(); j++) {
                if(i >= coins[j]) {
                    int min = result[i];
                    if(result[i - coins[j]] + 1 < min)
                        min = result[i - coins[j]] + 1;
                    result[i] = min;
                }
            }
        }
        if(result[amount] > amount)
            return -1;
        else
            return result[amount];
    }
};
發佈了30 篇原創文章 · 獲贊 1 · 訪問量 3809
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章