lintcode 669. 換硬幣 完全揹包

給出不同面額的硬幣以及一個總金額. 寫一個方法來計算給出的總金額可以換取的最少的硬幣數量. 如果已有硬幣的任意組合均無法與總金額面額相等, 那麼返回 -1.

樣例
樣例1

輸入:
[1, 2, 5]
11
輸出: 3
解釋: 11 = 5 + 5 + 1
樣例2

輸入: 
[2]
3
輸出: -1
注意事項
你可以假設每種硬幣均有無數個
總金額不會超過10000
硬幣的種類數不會超過500, 每種硬幣的面額不會超過100
class Solution {
public:
    /**
     * @param coins: a list of integer
     * @param amount: a total amount of money amount
     * @return: the fewest number of coins that you need to make up
     */
    int coinChange(vector<int> &coins, int amount) {
        // write your code here
        vector<int> dp(amount+1,INT_MAX-1);
        dp[0]=0;
        for (int i = 0; i < coins.size(); i++) {
            for(int j = coins[i];j<=amount;j++)
            {
                dp[j]=min(dp[j],dp[j-coins[i]]+1);
            }
        }
        if(dp[amount]==INT_MAX-1) return -1;
        return dp[amount];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章