Skip to content

Commit bda63d8

Browse files
authored
Update 0322-coin-change.kt
1 parent d274d41 commit bda63d8

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

kotlin/0322-coin-change.kt

+35-7
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,42 @@
1+
// DP
12
class Solution {
23
fun coinChange(coins: IntArray, amount: Int): Int {
3-
val dp = IntArray(amount+1){amount+1}
4+
val dp = IntArray (amount + 1) { amount + 1 }
45
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)
910
}
1011
}
1112
}
12-
return if(dp[amount]>amount) -1 else dp[amount]
13+
return if (dp[amount] > amount) -1 else dp[amount]
1314
}
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+
}

0 commit comments

Comments
 (0)