博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[CareerCup] 9.8 Represent N Cents 组成N分钱
阅读量:5080 次
发布时间:2019-06-12

本文共 2231 字,大约阅读时间需要 7 分钟。

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
cents = {1, 5, 10, 25}; vector
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
denoms = {25, 10, 5, 1}; vector
> m(n + 1, vector
(denoms.size())); return makeChange(n, denoms, 0, m); } int makeChange(int amount, vector
denoms, int idx, vector
> &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; }};

  

类似题目:

 

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

你可能感兴趣的文章
mac os命令参考
查看>>
maven打包上传到本地中央库
查看>>
教育类APP开发现新增长,多款APP该如何突围?
查看>>
打开3389
查看>>
React学习记录
查看>>
nginx常见内部参数,错误总结
查看>>
对象与类
查看>>
《奸的好人2》财色战场----笔记
查看>>
BZOJ 1834网络扩容题解
查看>>
bzoj1878
查看>>
【Vegas原创】Mysql绿色版安装方法
查看>>
设计模式之结构型模式
查看>>
Thrift Expected protocol id ffffff82 but got 0
查看>>
分享《去哪儿网》前端笔试题
查看>>
2013-07-04学习笔记二
查看>>
CP15 协处理器寄存器解读
查看>>
【codeforces 787B】Not Afraid
查看>>
【9111】高精度除法(高精度除高精度)
查看>>
【hihocoder 1312】搜索三·启发式搜索(普通广搜做法)
查看>>
JavaFX中ObservableValue类型
查看>>