Skip to content

Commit aaafef4

Browse files
authored
Create 1639-number-of-ways-to-form-a-target-string-given-a-dictionary.kt
1 parent f6168c3 commit aaafef4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
fun numWays(words: Array<String>, target: String): Int {
3+
val mod = 1000000000 + 7
4+
val m = words[0].length
5+
val n = target.length
6+
7+
val count = Array(m){IntArray(26)}
8+
for (w in words) {
9+
for ((i, c) in w.withIndex()) {
10+
count[i][c - 'a'] += 1
11+
}
12+
}
13+
14+
val dp = Array(n){LongArray(m){-1L}}
15+
16+
fun dfs(i: Int, k: Int): Long {
17+
if (i == n)
18+
return 1L
19+
if (k == m)
20+
return 0L
21+
if (dp[i][k] != -1L)
22+
return dp[i][k]
23+
24+
val c = target[i]
25+
dp[i][k] = dfs(i, k + 1)
26+
if(count[k][c - 'a'] != 0)
27+
dp[i][k] += count[k][c - 'a'] * dfs(i + 1, k + 1)
28+
29+
return dp[i][k] % mod
30+
}
31+
32+
return dfs(0, 0).toInt()
33+
}
34+
}

0 commit comments

Comments
 (0)