forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
62 lines (60 loc) · 1.09 KB
/
Solution.go
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
type Trie struct {
children [26]*Trie
v []int
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string, i int) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
node.v = append(node.v, i)
}
}
func (this *Trie) search(word string) []int {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return []int{}
}
node = node.children[c]
}
return node.v
}
func wordSquares(words []string) [][]string {
trie := newTrie()
for i, w := range words {
trie.insert(w, i)
}
ans := [][]string{}
var dfs func([]string)
dfs = func(t []string) {
if len(t) == len(words[0]) {
cp := make([]string, len(t))
copy(cp, t)
ans = append(ans, cp)
return
}
idx := len(t)
pref := []byte{}
for _, v := range t {
pref = append(pref, v[idx])
}
indexes := trie.search(string(pref))
for _, i := range indexes {
t = append(t, words[i])
dfs(t)
t = t[:len(t)-1]
}
}
for _, w := range words {
dfs([]string{w})
}
return ans
}