Approach
Depth-first search
For Sentence Similarity II, 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
- 47 lines of C++ from the credited upstream file 737.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 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.
1class Solution {2 public:3 bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2,4 vector<vector<string>>& pairs) {5 if (words1.size() != words2.size())6 return false;7 8 9 unordered_map<string, unordered_set<string>> graph;10 11 for (const vector<string>& pair : pairs) {12 graph[pair[1]].insert(pair[0]);13 graph[pair[0]].insert(pair[1]);14 }15 16 for (int i = 0; i < words1.size(); ++i) {17 if (words1[i] == words2[i])18 continue;19 if (!graph.contains(words1[i]))20 return false;21 if (!dfs(graph, words1[i], words2[i], {}))22 return false;23 }24 25 return true;26 }27 28 private:29 bool dfs(const unordered_map<string, unordered_set<string>>& graph,30 const string& source, const string& target,31 unordered_set<string>&& seen) {32 if (graph.at(source).contains(target))33 return true;34 35 seen.insert(source);36 37 for (const string& child : graph.at(source)) {38 if (seen.contains(child))39 continue;40 if (dfs(graph, child, target, std::move(seen)))41 return true;42 }43 44 return false;45 }46};47