硬幣表示

  • 有數量不限的硬幣,幣值爲25分、10分、5分和1分,請編寫代碼計算n分有幾種表示法。給定一個int n,請返回n分有幾種表示法。保證n小於等於100000,爲了防止溢出,請將答案Mod 1000000007。
  • 測試樣例: 6 返回:2
class Coins {
public:
    int countWays(int n) {
        // write code here
        int coins[4]={1,5,10,25};
        int dp[100001] = {0};       
        dp[0] = 1;
        for(int i = 0;i < 4;++i){
            for(int j = coins[i];j <= n;++j){
                dp[j] =(dp[j]+dp[j-coins[i]])%1000000007;               
            }
        }
        return dp[n];
    }
};
  • 更好理解的代碼是下面這樣的,可是時間複雜度比較高:
public class Coins {
    //硬幣的面值爲: 25,10,5,1
    public int countWays(int n) {
        return totalWays(n, 25);
    }

    public int totalWays(int remain, int curr){
        int next = 0;
        int ways = 0;
        switch (curr){
            case 25:
                next = 10;
                break;
            case 10:
                next = 5;
                break;
            case 5:
                next = 1;
                break;
            case 1:
                return 1; //注意若是next是1的話,那麼也就只有一種方法了
        }
        for(int i = 0; curr * i <= remain; i++){
            ways += totalWays(remain - curr * i, next);
        }
        return ways%1000000007;
    }
}
相關文章
相關標籤/搜索