forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjdalma.kt
95 lines (80 loc) ยท 3.05 KB
/
jdalma.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `decode-ways` {
fun numDecodings(s: String): Int {
return usingOptimizedDP(s)
}
/**
* 1. ๋ฌธ์์ด์ ์ฒซ ์ธ๋ฑ์ค๋ถํฐ DFS๋ก ํ์ธํ๋ฉด์ ๊ฒฐ๊ณผ๋ฅผ ์ฆ๊ฐ์ํจ๋ค. โ ์๊ฐ์ด๊ณผ
* 0๋ถํฐ ์์ํ๋ ๋ฌธ์์ด์ ์กด์ฌํ์ง ์๊ธฐ์ ๋ฐ๋ก 0์ผ๋ก ๋ฐํํ๊ณ ๊ทธ ๋ค ์ซ์๋ถํฐ DFS๋ฅผ ์ฐ์ด์ด ์คํํ๋ค.
* ์๊ฐ๋ณต์ก๋: O(2^n), ๊ณต๊ฐ๋ณต์ก๋: O(n)
*/
private fun usingDfs(s: String): Int {
fun dfs(index: Int): Int =
if (index == s.length) 1
else if (s[index] == '0') 0
else if (index + 1 < s.length && (s[index] == '1' || (s[index] == '2' && s[index + 1] < '7')) )
dfs(index + 1) + dfs(index + 2)
else dfs(index + 1)
return dfs(0)
}
/**
* 2. 1๋ฒ ํ์ด์์ ์ค๋ณต๋๋ ์ฐ์ฐ์ top-down ๋ฐฉํฅ์ผ๋ก ๋ฉ๋ชจ์ด์ ์ด์
์ ์ฉ
* ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(n)
*/
private fun usingMemoization(s: String): Int {
fun dfs(index: Int, mem: IntArray): Int {
println(index)
mem[index] = if (index == s.length) 1
else if (s[index] == '0') 0
else if (mem[index] != 0) mem[index]
else if (index + 1 < s.length && (s[index] == '1' || (s[index] == '2' && s[index + 1] < '7')) )
dfs(index + 1, mem) + dfs(index + 2, mem)
else dfs(index + 1, mem)
return mem[index]
}
return dfs(0, IntArray(s.length + 1) { 0 })
}
/**
* 3. ๋ง์ง๋ง ์ซ์๋ถํฐ bottom-up ๋ฐฉํฅ DP
* ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(n)
*/
private fun usingDP(s: String): Int {
val dp = IntArray(s.length + 1).apply {
this[s.length] = 1
}
(s.length - 1 downTo 0).forEach { index ->
if (s[index] == '0') dp[index] = 0
else if(index + 1 < s.length && (s[index] == '1' || (s[index] == '2' && s[index + 1] < '7')))
dp[index] = dp[index + 1] + dp[index + 2]
else dp[index] = dp[index + 1]
}
return dp[0]
}
/**
* 4. ๋ฐฐ์ด์ ์ฌ์ฉํ์ง ์๊ณ DP ์ ์ฉ
* ์๊ฐ๋ณต์ก๋: O(n), ๊ณต๊ฐ๋ณต์ก๋: O(1)
*/
private fun usingOptimizedDP(s: String): Int {
var (memo, result) = 0 to 1
(s.length - 1 downTo 0).forEach { index ->
var tmp = if (s[index] == '0') 0 else result
if (index + 1 < s.length && (s[index] == '1' || (s[index] == '2' && s[index + 1] < '7'))) {
tmp += memo
}
memo = result
result = tmp
}
return result
}
@Test
fun `์
๋ ฅ๋ฐ์ ๋ฌธ์์ด์ ๋์ฝ๋ฉ ๊ฐ๋ฅํ ๊ฒฝ์ฐ์ ์๋ฅผ ๋ฐํํ๋ค`() {
numDecodings("12") shouldBe 2
numDecodings("226") shouldBe 3
numDecodings("06") shouldBe 0
numDecodings("1011") shouldBe 2
numDecodings("10112266") shouldBe 8
numDecodings("1025") shouldBe 2
}
}