forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-squares.cpp
62 lines (54 loc) · 1.76 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
// 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 j = 0; j < words.size(); ++j) {
TrieNode* t = root;
for (int i = 0; i < words[j].size(); ++i) {
if (!t->children[words[j][i] - 'a']) {
t->children[words[j][i] - 'a'] = new TrieNode();
}
t = t->children[words[j][i] - 'a'];
t->indices.push_back(j);
}
}
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 (curr->size() >= words[0].length()) {
return result->emplace_back(*curr);
}
TrieNode *node = trie;
for (int i = 0; i < curr->size(); ++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();
}
}
};