forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
word-squares.cpp
63 lines (55 loc) · 1.77 KB
/
word-squares.cpp
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
// Time: O(n^2 * n!)
// Space: O(n^2)
class Solution {
private:
struct TrieNode {
vector<int> indices;
vector<TrieNode *> children;
TrieNode() : children(26, nullptr) {}
};
TrieNode *buildTrie(const vector<string>& words) {
TrieNode *root = new TrieNode();
for (int i = 0; i < size(words); ++i) {
TrieNode* t = root;
for (int j = 0; j < size(words[i]); ++j) {
if (!t->children[words[i][j] - 'a']) {
t->children[words[i][j] - 'a'] = new TrieNode();
}
t = t->children[words[i][j] - 'a'];
t->indices.emplace_back(i);
}
}
return root;
}
public:
vector<vector<string>> wordSquares(vector<string>& words) {
vector<vector<string>> result;
TrieNode *trie = buildTrie(words);
vector<string> curr;
for (const auto& s : words) {
curr.emplace_back(s);
wordSquaresHelper(words, trie, &curr, &result);
curr.pop_back();
}
return result;
}
private:
void wordSquaresHelper(const vector<string>& words, TrieNode *trie, vector<string> *curr,
vector<vector<string>> *result) {
if (size(*curr) == size(words[0])) {
result->emplace_back(*curr);
return;
}
TrieNode *node = trie;
for (int i = 0; i < size(*curr); ++i) {
if (!(node = node->children[(*curr)[i][curr->size()] - 'a'])) {
return;
}
}
for (const auto& i : node->indices) {
curr->emplace_back(words[i]);
wordSquaresHelper(words, trie, curr, result);
curr->pop_back();
}
}
};