-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
27c5cf0
commit 39a357b
Showing
2 changed files
with
38 additions
and
3 deletions.
There are no files selected for viewing
35 changes: 35 additions & 0 deletions
35
...ecember-LeetCoding-Challenge/Number of Ways to Form a Target String Given a Dictionary.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from collections import Counter | ||
from functools import lru_cache | ||
from typing import List | ||
|
||
|
||
class Solution: | ||
def numWays(self, words: List[str], target: str) -> int: | ||
count = [Counter() for _ in range(len(words[0]))] | ||
for word in words: | ||
for idx, ch in enumerate(word): | ||
count[idx][ch] += 1 | ||
|
||
@lru_cache(None) | ||
def dfs(i: int = 0, j: int = 0) -> int: | ||
if i == len(target): | ||
return 1 | ||
if j == len(words[0]): | ||
return 0 | ||
return (dfs(i, j+1) + dfs(i+1, j+1) * count[j][target[i]]) % int(1e9 + 7) | ||
|
||
return dfs() | ||
|
||
|
||
def main(): | ||
words = ['acca', 'bbbb', 'caca'] | ||
target = 'aba' | ||
assert Solution().numWays(words, target) == 6 | ||
|
||
words = ['abba', 'baab'] | ||
target = 'bab' | ||
assert Solution().numWays(words, target) == 4 | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters