|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -import java.util.Arrays; |
4 |
| - |
5 | 3 | public class _322 {
|
6 | 4 |
|
7 | 5 | public static class Solution1 {
|
| 6 | + /** |
| 7 | + * credit: https://leetcode.com/problems/coin-change-2/discuss/99212/Knapsack-problem-Java-solution-with-thinking-process-O(nm)-Time-and-O(m)-Space |
| 8 | + */ |
8 | 9 | public int coinChange(int[] coins, int amount) {
|
9 |
| - if (amount < 1) { |
10 |
| - return 0; |
11 |
| - } |
12 |
| - int[] count = new int[amount]; |
13 |
| - int result = helper(coins, amount, count); |
14 |
| - return result; |
15 |
| - } |
16 |
| - |
17 |
| - //remaining means the remaining coins after the last step; |
18 |
| - //count[remaining] means the minimum number of coins to sum up to remaining |
19 |
| - private int helper(int[] coins, int remaining, int[] count) { |
20 |
| - if (remaining < 0) { |
21 |
| - return -1;//not valid case, thus, per problem description, we should return -1 |
22 |
| - } |
23 |
| - if (remaining == 0) { |
24 |
| - return 0;//completed, this is also a base case for this recursive function |
25 |
| - } |
26 |
| - if (count[remaining - 1] != 0) { |
27 |
| - return count[remaining - 1];//already computed, so reuse it. |
28 |
| - } |
29 |
| - int min = Integer.MAX_VALUE; |
| 10 | + int[] dp = new int[amount + 1]; |
| 11 | + dp[0] = 1; |
30 | 12 | for (int coin : coins) {
|
31 |
| - int res = helper(coins, remaining - coin, count); |
32 |
| - if (res >= 0 && res < min) { |
33 |
| - min = 1 + res; |
34 |
| - } |
35 |
| - } |
36 |
| - return count[remaining - 1] = (min == Integer.MAX_VALUE) ? -1 : min; |
37 |
| - } |
38 |
| - } |
39 |
| - |
40 |
| - public static class Solution2 { |
41 |
| - //dp solution |
42 |
| - public int coinChange(int[] coins, int amount) { |
43 |
| - int max = amount + 1; |
44 |
| - int[] dp = new int[max]; |
45 |
| - Arrays.fill(dp, max);// initial the dp array with amount + 1 which is not valid case. |
46 |
| - dp[0] = 0;//initial amount 0 = 0; |
47 |
| - for (int i = 1; i <= amount; i++) { |
48 |
| - for (int j = 0; j < coins.length; j++) { |
49 |
| - if (coins[j] <= i) { |
50 |
| - //the dp[coins[j]] will ba a valid case, then if dp[i - coins[j]] is valid |
51 |
| - dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); |
52 |
| - // then we update dp[i], otherwise dp[i] = max; |
53 |
| - } |
| 13 | + for (int i = coin; i <= amount; i++) { |
| 14 | + dp[i] += dp[i - coin]; |
54 | 15 | }
|
55 | 16 | }
|
56 |
| - return dp[amount] > amount ? -1 : dp[amount]; |
| 17 | + return dp[amount]; |
57 | 18 | }
|
58 | 19 | }
|
59 | 20 |
|
|
0 commit comments