8.11 Coins

For example, if we have n = 100 cents:
makeChange(100) = makeChange(100 w/ 0 quater) + makeChange(100 w/ 1 quater) + makeChange(100 w/ 2 quater) + makeChange(100 w/ 3 quater) + makeChange(100 w/ 4 quater). What’s more, makeChange(100 w/ 1 quater) = makeChange(75 w/ 0 quarter).
Under each sub problem we have makeChange(100 w/ 0 quarter) = makeChange(100 w/ 0 quarter, 1 dime to 10 dime)…

Than’s mean: we can solve the question by accumulating all there results!

    //c++
    int helper(vector<int>& coins, int n, int idx){
        if(idx >= coins.size() - 1) return 1;
        int cntWays = 0;
        for (int i = 0; i*coins[idx] <= n; ++i) {
            cntWays += helper(coins, n - i*coins[idx], idx + 1);
        }
        return cntWays;
    }
    int makeChange(int n){
        vector<int> coins = {25, 10, 5, 1};
        return helper(coins, n, 0);
    }
    public static int makeChangeHelper(int[] coins, int n, int idx){
        if(idx >= coins.length-1) return 1;
        int amount = coins[idx], cntWays = 0;
        for(int i = 0; i*amount <= n; ++i){
            cntWays += makeChangeHelper(coins, n-i*amount, idx + 1);
        }
        return cntWays;
    }

    public static int makeChange(int n, int[] coins){
        return makeChangeHelper(coins, n, 0);
    }

However, the above code is not that optimal, because we keep recall makeChange(100 w/ …) several times. Therefore, the possible method to optimize it is by using extra space O(kn). By recording the certain amount ways, we will increase the speed. There is a basically the trade-off between memory and speed.

    public static int makeChangeHelper(int[] coins, int amount, int idx, int[][] mp){
        if(mp[amount][idx] > 0) return mp[amount][idx];
        if(idx >= coins.length-1) return 1;
        int cntWays = 0;
        for(int i = 0; i * coins[idx] <= amount; ++i){
            cntWays += makeChangeHelper(coins, amount - i*coins[idx], idx+1, mp);
        }
        mp[amount][idx] = cntWays;
        return cntWays;
    }
    public static int makeChange(int n, int[] coins){
        int[][] mp = new int[n+1][coins.length];
        return makeChangeHelper(coins,n,0,mp);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值