Skip to content

Commit 906d578

Browse files
refactor 322
1 parent 13a25a9 commit 906d578

File tree

1 file changed

+8
-47
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+8
-47
lines changed

src/main/java/com/fishercoder/solutions/_322.java

Lines changed: 8 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,20 @@
11
package com.fishercoder.solutions;
22

3-
import java.util.Arrays;
4-
53
public class _322 {
64

75
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+
*/
89
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;
3012
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];
5415
}
5516
}
56-
return dp[amount] > amount ? -1 : dp[amount];
17+
return dp[amount];
5718
}
5819
}
5920

0 commit comments

Comments
 (0)