Leetcode OJ --- 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.

 

解析:這題就是很明顯的DP問題,一開始想到是否可以使用貪心,后面發現是不能保證最小coin數目的,舉個例子,如果amount = 8, coins為[1, 3, 5, 6],我們會發現,采用貪心策略得到3(6,1,1),而實際正確值為2(5,3),之所以貪心法在這里不適用是因為貪心所作的決策並不能確保全局的最優,如果換作這樣的問題,提水,每桶都有一定量的水,怎樣才能最少次數運完所有的水,這樣肯定就是貪心選擇最多的水。因為每次提越多的水,最后的次數肯定最少。coin change 其實有兩種解決辦法,但是思想是一樣的,第一種,dp[n]為amount為n的change數目,那么我們從dp[1]開始就可以DP到dp[n],迭代關系式為,dp[n] = min(dp[n], dp[n-coins[m]]+1). 還有一種方法是使用遞歸的方法,有可能會造成memory exceed,遞推關系為count(n,m,coins) = min(count(n,m-1,coins), count(n-coins[m],m,coins)); 其中count表示尋找最少change的函數,n為amount,m為coins(排好序的)的下標。

Code:

class Solution {
private:
    const int INF = 0x7ffffffe;
public:
    int coinChange(vector<int>& coins, int amount) {
        sort(coins.begin(), coins.end());
        
        int result = count(amount, coins);
        if(result == INF){
            return -1;
        }
        else{
            return result;
        }
    }
    
    int count(int n,vector<int>& coins){
        if (n == 0){
            return 0;
        }
        if (coins.size() == 0){
            return -1;
        }
            
        vector<int> dp(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            int min2  = INF;
            for (int j = 0; j < coins.size(); j++) {
                if (i >= coins[j] && dp[i - coins[j]] != -1){
                    min2 = min(min2, dp[i - coins[j]] + 1);
                }
            }
            dp[i] = min2 == INF ? -1 : min2;
        }
        return dp[n];
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM