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.

難度:medium 通過率:25.9%

這道題老師在課上講了一下思路,利用數組f[i]表示金額爲i時的最小硬幣數,然後當金額爲i-coins[j]時,加上硬幣j,即f[i-coins[j]]+1和f[i]進行比較,取較小的值,動態更新數組,代碼實現如下:

class Solution {
public:
    int coinChange(vector<int>& coins, int amount) {
        int size = coins.size();
        vector<int> f(amount+1, -1);
        f[0] = 0;
        for(int i = 1; i <= amount; i++) {
            for(int j = 0; j < size; j++) {
                if(coins[j] <= i && f[i-coins[j]]!=-1&&(f[i-coins[j]]+1 < f[i] || f[i] == -1)) {
                    f[i] = f[i-coins[j]] + 1;
                }
            }
        }
        return f[amount];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章