面试题 08.11. 硬币

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/coin-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

动态规划

import java.util.Scanner;

class Solution {

    private static final int MOD = 1000000007;

    public int waysToChange(int n) {
        int[] coins = {1, 5, 10, 25};
        int[] dp = new int[n + 1];
        dp[0] = 1;
        for (int i = 0; i < coins.length; ++i) {
            for (int j = coins[i]; j <= n; ++j) {
                dp[j] = (dp[j] + dp[j - coins[i]]) % MOD;
            }
        }
        return dp[n];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(new Solution().waysToChange(in.nextInt()));
        }
    }
}

数学

class Solution {
    static final int MOD = 1000000007;

    public int waysToChange1(int n) {
        int ans = 0;
        for (int coin25 = 0; coin25 <= n / 25; ++coin25) {
            int r1 = n - coin25 * 25;
            for (int coin_10 = 0; coin_10 <= r1 / 10; ++coin_10) {
                int r2 = r1 - coin_10 * 10;
                for (int coin_5 = 0; coin_5 <= r2 / 5; ++coin_5) {
                    ans++;
                }
            }
        }
        return ans;
    }

    public int waysToChange2(int n) {
        int ans = 0;
        for (int coin25 = 0; coin25 <= n / 25; ++coin25) {
            int r1 = n - coin25 * 25;
            for (int coin_10 = 0; coin_10 <= r1 / 10; ++coin_10) {
                int r2 = r1 - coin_10 * 10;
                ans += r2 / 5 + 1;
            }
        }
        return ans;
    }

    public int waysToChange(int n) {
        int ans = 0;
        for (int coin25 = 0; coin25 <= n / 25; ++coin25) {
            int r1 = n - coin25 * 25;
            ans = (int) (ans + ((long) ((r1 / 5 + 1) + (r1 % 10 / 5 + 1)) * (r1 / 10 + 1) / 2 % MOD)) % MOD;
        }
        return ans;
    }
}
上一篇:final


下一篇:大聪明教你学Java | 没有绝对安全的系统