forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0518-coin-change-ii.kt
68 lines (57 loc) · 1.47 KB
/
0518-coin-change-ii.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* DP with O(n) memory
*/
class Solution {
fun change(amount: Int, coins: IntArray): Int {
val dp = IntArray(amount + 1)
dp[0] = 1
for (coin in coins) {
for (i in 1..amount) {
if (i - coin >= 0)
dp[i] += dp[i - coin]
}
}
return dp[amount]
}
}
/*
* DP with O(n^2) memory
*/
class Solution {
fun change(amount: Int, coins: IntArray): Int {
val dp = Array(coins.size) { IntArray(amount + 1) }
for (i in 0 until coins.size)
dp[i][0] = 1
for (i in 0..coins.lastIndex) {
for (j in 1..amount) {
if (i > 0) {
dp[i][j] += dp[i - 1][j]
}
if (j - coins[i] >= 0)
dp[i][j] += dp[i][j - coins[i]]
}
}
return dp[coins.lastIndex][amount]
}
}
/*
* DFS + Memo
*/
class Solution {
fun change(amount: Int, coins: IntArray): Int {
val cache = Array(coins.size) { IntArray(amount + 1) {-1} }
fun dfs(i: Int, a: Int): Int {
if (a == amount)
return 1
if (a > amount)
return 0
if (i == coins.size)
return 0
if (cache[i][a] != -1)
return cache[i][a]
cache[i][a] = dfs(i, a + coins[i]) + dfs(i + 1, a)
return cache[i][a]
}
return dfs(0, 0)
}
}