代码拉取完成,页面将自动刷新
// 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();
}
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。