当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.程序员面试金典.0811.Coin 硬币

LeetCode.程序员面试金典.0811.Coin 硬币

题目描述

《程序员面试金典(第 6 版)》面试题 08.11. 硬币
https://leetcode-cn.com/problems/coin-lcci/

518 Coin Change 2
https://leetcode-cn.com/problems/coin-change-2/

硬币。给定数量不限的硬币,币值为25分、10分、5分和1分,编写代码计算n分有几种表示法。(结果可能会很大,你需要将结果模上1000000007)

示例1:

 输入: n = 5
 输出:2
 解释: 有两种方式可以凑成总金额:
5=5
5=1+1+1+1+1

示例2:

 输入: n = 10
 输出:4
 解释: 有四种方式可以凑成总金额:
10=10
10=5+5
10=5+1+1+1+1+1
10=1+1+1+1+1+1+1+1+1+1

注意:
你可以假设: 0 <= n (总金额) <= 1000000


相似题目

LeetCode.322.Coin Change 零钱兑换
LeetCode.程序员面试金典.0811.Coin 硬币


解题过程

设 dp[i,j] 表示用前 i 个硬币构成面值 j 的方案数

private static class SolutionV2020 {
    public int waysToChange(int n) {
        int[] coin = {1, 5, 10, 25};
        // dp[i][j] 表示用前 i 个硬币构成面值 j 的方案数,则有 dp[i][j] = dp[i-1][j] + dp[i][j-ci] , ci表示第i个硬币的面值
        int[][] dp = new int[5][n + 1];
        // 硬币1组成任意金额的方案只有1种
        Arrays.fill(dp[1], 1);
        // 不管多少个硬币,组成面值0的方案只有1种
        for (int i = 1; i <= 4; i++) {
            dp[i][0] = 1;
        }
        for (int i = 2; i <= 4; i++) {
            for (int j = 1; j <= n; j++) {
                if (j < coin[i - 1]) {
                    dp[i][j] = dp[i - 1][j] % 1000000007;
                } else {
                    dp[i][j] = (dp[i - 1][j] + dp[i][j - coin[i - 1]]) % 1000000007;
                }
            }
        }
        return dp[4][n];
    }
}

GitHub代码

algorithms/leetcode/crack/_0811_Coin.java
https://github.com/masikkk/algorithms/blob/master/leetcode/crack/_0811_Coin.java


上一篇 LeetCode.剑指offer.051.数组中的逆序对

下一篇 LeetCode.199.Binary Tree Right Side View 二叉树的右视图

阅读
评论
414
阅读预计1分钟
创建日期 2020-04-23
修改日期 2020-04-23
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论