Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 2cb7d89

Browse files
update 322
1 parent cc2b1ed commit 2cb7d89

File tree

1 file changed

+22
-5
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+22
-5
lines changed

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

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,31 @@ public static class Solution1 {
77
* credit: https://leetcode.com/problems/coin-change-2/discuss/99212/Knapsack-problem-Java-solution-with-thinking-process-O(nm)-Time-and-O(m)-Space
88
*/
99
public int coinChange(int[] coins, int amount) {
10-
int[] dp = new int[amount + 1];
11-
dp[0] = 1;
10+
if (amount < 1) {
11+
return 0;
12+
}
13+
return coinChange(coins, amount, new int[amount]);
14+
}
15+
16+
private int coinChange(int[] coins, int rem, int[] count) {
17+
if (rem < 0) {
18+
return -1;
19+
}
20+
if (rem == 0) {
21+
return 0;
22+
}
23+
if (count[rem - 1] != 0) {
24+
return count[rem - 1];
25+
}
26+
int min = Integer.MAX_VALUE;
1227
for (int coin : coins) {
13-
for (int i = coin; i <= amount; i++) {
14-
dp[i] += dp[i - coin];
28+
int res = coinChange(coins, rem - coin, count);
29+
if (res >= 0 && res < min) {
30+
min = 1 + res;
1531
}
1632
}
17-
return dp[amount];
33+
count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
34+
return count[rem - 1];
1835
}
1936
}
2037

0 commit comments

Comments
 (0)