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];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章