|
| 1 | +// Time: O(n^2 * n!) |
| 2 | +// Space: O(n^2) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +private: |
| 6 | + struct TrieNode { |
| 7 | + vector<int> indices; |
| 8 | + vector<TrieNode *> children; |
| 9 | + TrieNode() : children(26, nullptr) {} |
| 10 | + }; |
| 11 | + |
| 12 | + TrieNode *buildTrie(const vector<string>& words) { |
| 13 | + TrieNode *root = new TrieNode(); |
| 14 | + for (int j = 0; j < words.size(); ++j) { |
| 15 | + TrieNode* t = root; |
| 16 | + for (int i = 0; i < words[j].size(); ++i) { |
| 17 | + if (!t->children[words[j][i] - 'a']) { |
| 18 | + t->children[words[j][i] - 'a'] = new TrieNode(); |
| 19 | + } |
| 20 | + t = t->children[words[j][i] - 'a']; |
| 21 | + t->indices.push_back(j); |
| 22 | + } |
| 23 | + } |
| 24 | + return root; |
| 25 | + } |
| 26 | + |
| 27 | +public: |
| 28 | + vector<vector<string>> wordSquares(vector<string>& words) { |
| 29 | + vector<vector<string>> result; |
| 30 | + |
| 31 | + TrieNode *trie = buildTrie(words); |
| 32 | + vector<string> curr; |
| 33 | + for (const auto& s : words) { |
| 34 | + curr.emplace_back(s); |
| 35 | + wordSquaresHelper(words, trie, &curr, &result); |
| 36 | + curr.pop_back(); |
| 37 | + } |
| 38 | + |
| 39 | + return result; |
| 40 | + } |
| 41 | + |
| 42 | +private: |
| 43 | + void wordSquaresHelper(const vector<string>& words, TrieNode *trie, vector<string> *curr, |
| 44 | + vector<vector<string>> *result) { |
| 45 | + if (curr->size() >= words[0].length()) { |
| 46 | + return result->emplace_back(*curr); |
| 47 | + } |
| 48 | + |
| 49 | + TrieNode *node = trie; |
| 50 | + for (int i = 0; i < curr->size(); ++i) { |
| 51 | + if (!(node = node->children[(*curr)[i][curr->size()] - 'a'])) { |
| 52 | + return; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + for (const auto& i : node->indices) { |
| 57 | + curr->emplace_back(words[i]); |
| 58 | + wordSquaresHelper(words, trie, curr, result); |
| 59 | + curr->pop_back(); |
| 60 | + } |
| 61 | + } |
| 62 | +}; |
0 commit comments