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

class Solution { //完全背包问题
public:
    const int inf = 9999999;
    int coinChange(vector<int>& coins, int amount) {
        vector<int> cnt(amount+1, inf);
        cnt[0] = 0;
        for(int i=0; i<coins.size(); i++)
            for(int j = coins[i]; j<=amount; j++)
                //if(j == coins[i] )
                   // cnt[j] = 1;
                //else
                    //cnt[j] = min(cnt[j], cnt[j-coins[i]]+1);
                cnt[j] = (j == coins[i])? 1: min(cnt[j], cnt[j - coins[i]]+1);
        return cnt[amount] == inf? -1: cnt[amount];
    }
};
posted @ 2018-12-03 21:38  A-Little-Nut  阅读(159)  评论(0编辑  收藏  举报