-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy path1258. Synonymous Sentences.py
39 lines (31 loc) · 1.01 KB
/
1258. Synonymous Sentences.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
import collections
from typing import List
class Solution:
def generateSentences(self, synonyms: List[List[str]], text: str) -> List[str]:
g = collections.defaultdict(set)
for u, v in synonyms:
g[u].add(v)
g[v].add(u)
def dfs(u, cc):
if u not in cc:
cc.add(u)
for v in g[u]:
dfs(v, cc)
original_sentence = text.split()
sentence_list = []
def bracktrack(seq):
if len(seq) == len(original_sentence):
sentence_list.append(' '.join(seq))
else:
word = original_sentence[len(seq)]
choices = set()
if word in g:
dfs(word, choices)
else:
choices.add(word)
for w in sorted(choices):
seq.append(w)
bracktrack(seq)
seq.pop()
bracktrack([])
return sentence_list