[CareerCup] 9.8 Represent N Cents 组成N分钱

本文提供了一种使用动态规划计算给定金额下不同硬币组合总数的方法。通过Java、Python和C++等语言实现了该算法,并给出了详细的代码示例。

9.8 Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent), write code to calculate the number of ways of representing n cents.

给定一个钱数,用quarter,dime,nickle和penny来表示的方法总和。

Java:

public class Solution {
    /**
     * @param n an integer
     * @return an integer
     */
    public int waysNCents(int n) {
        int[] f = new int[n+1];
        f[0] = 1;
        int[] cents = new int[]{1, 5, 10, 25};
        for (int i = 0; i < 4; i++) 
            for (int j = 1; j <= n; j++) {
                if (j >= cents[i]) {
                    f[j] += f[j-cents[i]];
                }
            }
        return f[n];
    }
} 

Python:

class Solution:
    # @param {int} n an integer
    # @return {int} an integer
    def waysNCents(self, n):
        # Write your code here
        cents = [1, 5, 10, 25]
        ways = [0 for _ in xrange(n + 1)]
        
        ways[0] = 1
        for cent in cents:
            for j in xrange(cent, n + 1):
                ways[j] += ways[j - cent]
        
        return ways[n]

C++:

class Solution {
public:
    /**
     * @param n an integer
     * @return an integer
     */
    int waysNCents(int n) {
        // Write your code here
        vector<int> cents = {1, 5, 10, 25};
        vector<int> ways(n + 1);

        ways[0] = 1;
        for (int i = 0; i < 4; ++i)
            for (int j = cents[i]; j <= n; ++j)
                ways[j] += ways[j - cents[i]];

        return ways[n];
    }
};    

C++:

class Solution {
public:
    int makeChange(int n) {
        vector<int> denoms = {25, 10, 5, 1};
        vector<vector<int> > m(n + 1, vector<int>(denoms.size()));
        return makeChange(n, denoms, 0, m);
    }
    int makeChange(int amount, vector<int> denoms, int idx, vector<vector<int> > &m) {
        if (m[amount][idx] > 0) return m[amount][idx];
        if (idx >= denoms.size() - 1) return 1;
        int val = denoms[idx], res = 0;
        for (int i = 0; i * val <= amount; ++i) {
            int rem = amount - i * val;
            res += makeChange(rem, denoms, idx + 1, m);
        }
        m[amount][idx] = res;
        return res;
    }
};

  

类似题目:

[LeetCode] 322. Coin Change 硬币找零

 

CareerCup Questions List 职业杯题目列表

转载于:https://www.cnblogs.com/lightwindy/p/8674187.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值