File tree Expand file tree Collapse file tree 1 file changed +13
-14
lines changed Expand file tree Collapse file tree 1 file changed +13
-14
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int coinChange (int [] coins , int amount ) {
3
- if (amount < 1 ) {
4
- return 0 ;
5
- }
6
- return coinChange (coins , amount , new int [amount ]);
3
+ Integer [] memo = new Integer [amount + 1 ];
4
+ return coinChangeMemoization (coins , amount , memo );
7
5
}
8
-
9
- private int coinChange (int [] coins , int amount , int [] memo ) {
6
+
7
+ private int coinChangeMemoization (int [] coins , int amount , Integer [] memo ) {
10
8
if (amount < 0 ) {
11
9
return -1 ;
12
10
}
13
11
if (amount == 0 ) {
14
12
return 0 ;
15
13
}
16
- if (memo [amount - 1 ] != 0 ) {
17
- return memo [amount - 1 ];
14
+ if (memo [amount ] != null ) {
15
+ return memo [amount ];
18
16
}
19
- int min = Integer .MAX_VALUE ;
17
+ int minCount = Integer .MAX_VALUE ;
20
18
for (int coin : coins ) {
21
- int res = coinChange (coins , amount - coin , memo );
22
- if (res >= 0 && res < min ) {
23
- min = 1 + res ;
19
+ int count = coinChangeMemoization (coins , amount - coin , memo );
20
+ if (count == - 1 ) {
21
+ continue ;
24
22
}
23
+ minCount = Math .min (minCount , count + 1 );
25
24
}
26
- memo [amount - 1 ] = min == Integer .MAX_VALUE ? -1 : min ;
27
- return memo [amount - 1 ];
25
+ memo [amount ] = minCount == Integer .MAX_VALUE ? -1 : minCount ;
26
+ return memo [amount ];
28
27
}
29
28
}
You can’t perform that action at this time.
0 commit comments