forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-ways-to-form-a-target-string-given-a-dictionary.py
46 lines (39 loc) · 1.4 KB
/
number-of-ways-to-form-a-target-string-given-a-dictionary.py
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
# Time: O(l * (w + n)), l is the length of a word, w is the number of words, n is the length of target
# Space: O(n)
import collections
# optimized from Solution2
class Solution(object):
def numWays(self, words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
MOD = 10**9+7
dp = [0]*(len(target)+1)
dp[0] = 1
for i in xrange(len(words[0])):
count = collections.Counter(w[i] for w in words)
for j in reversed(xrange(len(target))):
dp[j+1] += dp[j]*count[target[j]] % MOD
return dp[-1] % MOD
# Time: O(l * (w + n)), l is the length of a word, w is the number of words, n is the length of target
# Space: O(n)
import collections
class Solution2(object):
def numWays(self, words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
MOD = 10**9+7
# dp[i+1][j+1]: number of ways of target[0..j] using count[0..i].
dp = [[0]*(len(target)+1) for _ in xrange(2)]
for i in xrange(len(dp)):
dp[i][0] = 1
for i in xrange(len(words[0])):
count = collections.Counter(w[i] for w in words)
for j in reversed(xrange(len(target))):
dp[(i+1)%2][j+1] = dp[i%2][j+1]+dp[i%2][j]*count[target[j]] % MOD
return dp[(len(words[0]))%2][-1] % MOD