From 0d2b107105197c9d32f3ad6806326728f0cdec7e Mon Sep 17 00:00:00 2001 From: algorithmzuo Date: Tue, 4 Apr 2023 19:43:59 +0800 Subject: [PATCH] modify code --- .../第03期/mca_09/Code05_CoinChange.java | 73 ++++++++++++++++--- 1 file changed, 62 insertions(+), 11 deletions(-) diff --git a/MCA算法突击课/第03期/mca_09/Code05_CoinChange.java b/MCA算法突击课/第03期/mca_09/Code05_CoinChange.java index 28594e4..218b3e5 100644 --- a/MCA算法突击课/第03期/mca_09/Code05_CoinChange.java +++ b/MCA算法突击课/第03期/mca_09/Code05_CoinChange.java @@ -7,22 +7,73 @@ package 第03期.mca_09; // 测试链接 : https://leetcode.cn/problems/coin-change-ii/ public class Code05_CoinChange { - public static int change(int aim, int[] arr) { - if (arr == null || arr.length == 0 || aim < 0) { + public static int change1(int aim, int[] arr) { + return process1(arr, 0, aim); + } + + public static int process1(int[] arr, int i, int j) { + if (j < 0) { + return 0; + } + if (i == arr.length) { + return j == 0 ? 1 : 0; + } + return process1(arr, i + 1, j) + process1(arr, i, j - arr[i]); + } + + public static int change2(int aim, int[] arr) { + int n = arr.length; + int[][] dp = new int[n][aim + 1]; + for (int i = 0; i < n; i++) { + for (int j = 0; j <= aim; j++) { + dp[i][j] = -1; + } + } + return process2(arr, 0, aim, dp); + } + + public static int process2(int[] arr, int i, int j, int[][] dp) { + if (j < 0) { return 0; } - int N = arr.length; - int[][] dp = new int[N + 1][aim + 1]; - dp[N][0] = 1; - for (int index = N - 1; index >= 0; index--) { - for (int rest = 0; rest <= aim; rest++) { - dp[index][rest] = dp[index + 1][rest]; - if (rest - arr[index] >= 0) { - dp[index][rest] += dp[index][rest - arr[index]]; + if (i == arr.length) { + return j == 0 ? 1 : 0; + } + if (dp[i][j] != -1) { + return dp[i][j]; + } + int ans = process2(arr, i + 1, j, dp) + process2(arr, i, j - arr[i], dp); + dp[i][j] = ans; + return ans; + } + + public static int change3(int aim, int[] arr) { + int n = arr.length; + int[][] dp = new int[n + 1][aim + 1]; + dp[n][0] = 1; + for (int i = n - 1; i >= 0; i--) { + for (int j = 0; j <= aim; j++) { + dp[i][j] = dp[i + 1][j]; + if (j - arr[i] >= 0) { + dp[i][j] += dp[i][j - arr[i]]; } } } return dp[0][aim]; } -} + public static int change4(int aim, int[] arr) { + int n = arr.length; + int[] dp = new int[aim + 1]; + dp[0] = 1; + for (int i = n - 1; i >= 0; i--) { + for (int j = 0; j <= aim; j++) { + if (j - arr[i] >= 0) { + dp[j] += dp[j - arr[i]]; + } + } + } + return dp[aim]; + } + +} \ No newline at end of file