File tree 1 file changed +35
-7
lines changed
1 file changed +35
-7
lines changed Original file line number Diff line number Diff line change
1
+ // DP
1
2
class Solution {
2
3
fun coinChange (coins : IntArray , amount : Int ): Int {
3
- val dp = IntArray (amount+ 1 ){ amount+ 1 }
4
+ val dp = IntArray (amount + 1 ) { amount + 1 }
4
5
dp[0 ] = 0
5
- for (i in 0 .. amount){
6
- for (j in 0 until coins.size){
7
- if (coins[j]<= i) {
8
- dp[i] = minOf(dp[i], dp[i- coins[j]]+ 1 )
6
+ for (i in 0 .. amount) {
7
+ for (j in 0 until coins.size) {
8
+ if (coins[j] <= i) {
9
+ dp[i] = minOf(dp[i], dp[i - coins[j]] + 1 )
9
10
}
10
11
}
11
12
}
12
- return if (dp[amount]> amount) - 1 else dp[amount]
13
+ return if (dp[amount] > amount) - 1 else dp[amount]
13
14
}
14
- }
15
+ }
16
+
17
+ // Recursion + memoization
18
+ class Solution {
19
+ fun coinChange (coins : IntArray , amount : Int ): Int {
20
+ val dp = IntArray (amount + 1 ) { - 1 }
21
+
22
+ fun dfs (amount : Int ): Int {
23
+ if (amount == 0 ) return 0
24
+ if (dp[amount] != - 1 ) return dp[amount]
25
+
26
+ var res = Integer .MAX_VALUE
27
+ for (coin in coins) {
28
+ if (amount - coin >= 0 ) {
29
+ var count = dfs(amount - coin)
30
+ if (count != Integer .MAX_VALUE )
31
+ res = minOf(res, count + 1 )
32
+ }
33
+ }
34
+
35
+ dp[amount] = res
36
+ return res
37
+ }
38
+
39
+ val res = dfs(amount)
40
+ return if (res == Integer .MAX_VALUE ) - 1 else res
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments