Approach
Depth-first search
For Word Pattern 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
- 52 lines of C++ from the credited upstream file 291.cpp.
- The implementation visibly relies on hash lookup.
- 1 loop block 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 wordPatternMatch(string pattern, string s) {4 return isMatch(pattern, 0, s, 0, unordered_map<char, string>(),5 unordered_set<string>());6 }7 8 private:9 bool isMatch(const string& pattern, int i, const string& s, int j,10 unordered_map<char, string>&& charToString,11 unordered_set<string>&& seen) {12 if (i == pattern.length() && j == s.length())13 return true;14 if (i == pattern.length() || j == s.length())15 return false;16 17 const char c = pattern[i];18 19 if (const auto it = charToString.find(c); it != charToString.cend()) {20 const string& t = it->second;21 22 if (s.substr(j).find(t) == string::npos)23 return false;24 25 26 return isMatch(pattern, i + 1, s, j + t.length(), std::move(charToString),27 std::move(seen));28 }29 30 for (int k = j; k < s.length(); ++k) {31 const string& t = s.substr(j, k - j + 1);32 33 34 if (seen.contains(t))35 continue;36 37 charToString[c] = t;38 seen.insert(t);39 40 if (isMatch(pattern, i + 1, s, k + 1, std::move(charToString),41 std::move(seen)))42 return true;43 44 45 charToString.erase(c);46 seen.erase(t);47 }48 49 return false;50 }51};52