Skip to content

Commit f3b2304

Browse files
authored
Create 1220-count-vowels-permutation.kt
1 parent dc0eb83 commit f3b2304

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
//DP
2+
class Solution {
3+
fun countVowelPermutation(n: Int): Int {
4+
val mod = 1_000_000_000 + 7
5+
val dp = Array (n + 1) { LongArray (5) }
6+
7+
for (j in 0 until 5)
8+
dp[1][j] = 1
9+
10+
val a = 0
11+
val e = 1
12+
val i = 2
13+
val o = 3
14+
val u = 4
15+
16+
for (j in 2..n) {
17+
dp[j][a] = 0L + (dp[j - 1][e] + dp[j - 1][i] + dp[j - 1][u]) % mod
18+
dp[j][e] = 0L + (dp[j - 1][a] + dp[j - 1][i]) % mod
19+
dp[j][i] = 0L + (dp[j - 1][e] + dp[j - 1][o]) % mod
20+
dp[j][o] = 0L + (dp[j - 1][i]) % mod
21+
dp[j][u] = 0L + (dp[j - 1][i] + dp[j - 1][o]) % mod
22+
}
23+
24+
return (dp[n].sum()!! % mod).toInt()
25+
}
26+
}
27+
28+
//recursion + memoization
29+
class Solution {
30+
fun countVowelPermutation(n: Int): Int {
31+
val mod = 1_000_000_000 + 7
32+
val dp = Array (n) { IntArray (5) { -1 } }
33+
34+
val a = 0
35+
val e = 1
36+
val i = 2
37+
val o = 3
38+
val u = 4
39+
40+
val follow = mapOf(
41+
a to listOf(e),
42+
e to listOf(a, i),
43+
i to listOf(a, e, o, u),
44+
o to listOf(i, u),
45+
u to listOf(a)
46+
)
47+
48+
fun dfs(idx: Int, prev: Int): Int {
49+
if (idx == n) return 1
50+
if (dp[idx][prev] != -1) return dp[idx][prev]
51+
52+
var res = 0
53+
follow[prev]?.forEach {
54+
res = (res + dfs(idx + 1, it)) % mod
55+
}
56+
57+
dp[idx][prev] = res
58+
return res
59+
}
60+
61+
var res = 0
62+
follow.keys.forEach {
63+
res = (res + dfs(1, it)) % mod
64+
}
65+
66+
return res
67+
}
68+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy