Skip to content

Commit 1e2e1d4

Browse files
authored
Create 1639-number-of-ways-to-form-a-target-string-given-a-dictionary.js
1 parent cb03069 commit 1e2e1d4

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {string[]} words
3+
* @param {string} target
4+
* @return {number}
5+
*/
6+
const numWays = function (words, target) {
7+
const m = words[0].length
8+
const n = target.length
9+
const memo = Array.from({ length: m }, () => Array(n))
10+
const charAtIndexCnt = Array.from({ length: 128 }, () => Array(m).fill(0))
11+
const mod = 10 ** 9 + 7
12+
for (let word of words) {
13+
for (let i = 0; i < m; i++) {
14+
charAtIndexCnt[word.charCodeAt(i)][i] += 1
15+
}
16+
}
17+
18+
return dp(0, 0)
19+
function dp(k, i) {
20+
// found one
21+
if (i == n) return 1
22+
// not found
23+
if (k == m) return 0
24+
if (memo[k][i] != null) return memo[k][i]
25+
const c = target.charCodeAt(i)
26+
// skip k_th char
27+
let ans = dp(k + 1, i)
28+
if (charAtIndexCnt[c][k] > 0) {
29+
ans += dp(k + 1, i + 1) * charAtIndexCnt[c][k]
30+
ans %= mod
31+
}
32+
return (memo[k][i] = ans)
33+
}
34+
}

0 commit comments

Comments
 (0)