File tree 1 file changed +22
-5
lines changed
src/main/java/com/fishercoder/solutions
1 file changed +22
-5
lines changed Original file line number Diff line number Diff line change @@ -7,14 +7,31 @@ public static class Solution1 {
7
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
9
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 ;
12
27
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 ;
15
31
}
16
32
}
17
- return dp [amount ];
33
+ count [rem - 1 ] = (min == Integer .MAX_VALUE ) ? -1 : min ;
34
+ return count [rem - 1 ];
18
35
}
19
36
}
20
37
You can’t perform that action at this time.
0 commit comments