-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.py
62 lines (48 loc) · 1.92 KB
/
solution.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# union-find + backTracking
class Solution:
def generateSentences(self, synonyms, text):
group = {}
for item in synonyms :
word1 = item[0]
word2 = item[1]
if word1 not in group :
group[word1] = word1
if word2 not in group :
group[word2] = word2
while group[word1] != group[group[word1]] :
group[word1] = group[group[word1]]
while group[word2] != group[group[word2]] :
group[word2] = group[group[word2]]
if group[word1] != group[word2] :
group[group[word2]] = group[word1]
group[word2] = group[word1]
relatives = {}
for key in group :
while group[key] != group[group[key]] :
group[key] = group[group[key]]
parent = group[key]
if parent not in relatives :
relatives[parent] = []
relatives[parent].append(key)
relatives[key] = relatives[parent]
for key in group :
if group[key] == key :
relatives[key].sort()
result = []
self.backTracking(text.split(' '),relatives,0,[],result )
return result
def backTracking(self,sentense,relatives,index,sequence,result) :
if index == len(sentense) :
result.append(" ".join(sequence))
return
word = sentense[index]
if word in relatives :
replaces = relatives[word]
for w in replaces :
sequence.append(w)
self.backTracking(sentense,relatives,index+1,sequence,result)
sequence.pop()
else :
sequence.append(word)
self.backTracking(sentense,relatives,index+1,sequence,result)
sequence.pop()