-
Notifications
You must be signed in to change notification settings - Fork 22
/
425.word-squares.cpp
106 lines (88 loc) · 2.19 KB
/
425.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
class TrieNode {
public:
unordered_map<char, TrieNode *> children;
bool isWord = false;
vector<string> words;
~TrieNode(){
for (auto it: children){
delete it.second;
}
}
};
class Trie {
TrieNode *root;
public:
Trie()
{
this->root = new TrieNode();
}
void addWord(string &word)
{
TrieNode *cur = this->root;
for(auto i = 0; i < word.size(); ++i)
{
cur->words.push_back(word);
if (cur->children.count(word[i]) == 0)
{
cur->children[word[i]] = new TrieNode();
}
cur = cur->children[word[i]];
}
cur->isWord = true;
}
vector<string> prefixWords(string prefix)
{
TrieNode *cur = this->root;
for (auto i = 0; i < prefix.size(); ++i) {
if (cur->children.count(prefix[i]) == 0)
{
return vector<string>();
}
cur = cur->children[prefix[i]];
}
return cur->words;
}
~Trie()
{
delete this->root;
}
};
class Solution {
private:
Trie trie;
void dfs(vector<string>& words, vector<string>& ans, vector<vector<string>> &res)
{
if (ans.size() == words[0].size())
{
res.push_back(ans);
return;
}
string prefix = "";
int size = ans.size();
for (auto i = 0; i < size; ++i)
{
prefix += ans[i][size];
}
vector<string> candidates = trie.prefixWords(prefix);
for (auto i = 0; i < candidates.size(); ++i)
{
ans.push_back(candidates[i]);
dfs(words, ans, res);
ans.pop_back();
}
}
void buildTrie(vector<string>& words){
for (auto i = 0; i < words.size(); ++i)
{
trie.addWord(words[i]);
}
}
public:
vector<vector<string>> wordSquares(vector<string>& words) {
buildTrie(words);
vector<vector<string>> res;
vector<string> ans;
dfs(words, ans, res);
return res;
}
};