Approach
Depth-first search
For Word Squares, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 88 lines of C++ from the credited upstream file 425.cpp.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct TrieNode {2 vector<shared_ptr<TrieNode>> children;3 vector<const string*> startsWith;4 TrieNode() : children(26) {}5};6 7class Trie {8 public:9 Trie(const vector<string>& words) {10 for (const string& word : words)11 insert(word);12 }13 14 vector<const string*> findBy(const string& prefix) {15 shared_ptr<TrieNode> node = root;16 for (const char c : prefix) {17 const int i = c - 'a';18 if (node->children[i] == nullptr)19 return {};20 node = node->children[i];21 }22 return node->startsWith;23 }24 25 private:26 shared_ptr<TrieNode> root = make_shared<TrieNode>();27 28 void insert(const string& word) {29 shared_ptr<TrieNode> node = root;30 for (const char c : word) {31 const int i = c - 'a';32 if (node->children[i] == nullptr)33 node->children[i] = make_shared<TrieNode>();34 node = node->children[i];35 node->startsWith.push_back(&word);36 }37 }38};39 40class Solution {41 public:42 vector<vector<string>> wordSquares(vector<string>& words) {43 if (words.empty())44 return {};45 46 const int n = words[0].length();47 vector<vector<string>> ans;48 vector<string> path;49 Trie trie(words);50 51 for (const string& word : words) {52 path.push_back(word);53 dfs(trie, n, path, ans);54 path.pop_back();55 }56 57 return ans;58 }59 60 private:61 void dfs(Trie& trie, const int n, vector<string>& path,62 vector<vector<string>>& ans) {63 if (path.size() == n) {64 ans.push_back(path);65 return;66 }67 68 const string prefix = getPrefix(path);69 70 for (const string* s : trie.findBy(prefix)) {71 path.push_back(*s);72 dfs(trie, n, path, ans);73 path.pop_back();74 }75 }76 77 78 79 80 string getPrefix(const vector<string>& path) {81 string prefix;82 const int index = path.size();83 for (const string& s : path)84 prefix += s[index];85 return prefix;86 }87};88