forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
67 lines (61 loc) · 1.71 KB
/
Solution.java
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
63
64
65
66
67
class Trie {
Trie[] children = new Trie[26];
List<Integer> v = new ArrayList<>();
void insert(String word, int i) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
node.v.add(i);
}
}
List<Integer> search(String pref) {
Trie node = this;
for (char c : pref.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return Collections.emptyList();
}
node = node.children[c];
}
return node.v;
}
}
class Solution {
private Trie trie = new Trie();
private String[] words;
private List<List<String>> ans = new ArrayList<>();
public List<List<String>> wordSquares(String[] words) {
this.words = words;
for (int i = 0; i < words.length; ++i) {
trie.insert(words[i], i);
}
List<String> t = new ArrayList<>();
for (String w : words) {
t.add(w);
dfs(t);
t.remove(t.size() - 1);
}
return ans;
}
private void dfs(List<String> t) {
if (t.size() == words[0].length()) {
ans.add(new ArrayList<>(t));
return;
}
int idx = t.size();
StringBuilder pref = new StringBuilder();
for (String x : t) {
pref.append(x.charAt(idx));
}
List<Integer> indexes = trie.search(pref.toString());
for (int i : indexes) {
t.add(words[i]);
dfs(t);
t.remove(t.size() - 1);
}
}
}