Approach
Depth-first search
For Isscramble, 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
- 42 lines of C++ from the credited upstream file isScramble.cpp.
- The implementation visibly relies on ordered lookup.
- 2 loop blocks detected.
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.
123 4class Solution {5 public:6 bool isScramble(string s1, string s2) {7 if(s1.size() != s2.size())8 return false;9 return isScramble(s1.size(), s1.begin(), s2.begin());10 }11 private:12 typedef string::const_iterator Iterator;13 map<tuple<int, Iterator, Iterator>, bool> hash;14 15 bool isScramble(int n, Iterator s1, Iterator s2) {16 17 if( hash.find(make_tuple(n, s1, s2)) != hash.end()) return hash[make_tuple(n, s1, s2)];18 19 if(n == 1) return *s1 == *s2;20 21 22 int value1 = 0, value2=0;23 for (auto it1 = s1, it2 = s2; it1 != s1 + n; ++it1, ++it2) {24 value1 += (*it1-'a');25 value2 += (*it2-'a');26 }27 if (value1 != value2)28 return hash[make_tuple(n, s1, s2)] = false; 29 30 31 for(int k = 1; k < n; ++k) {32 if((isScramble(k, s1, s2) && isScramble(n - k, s1 + k, s2 + k))33 || (isScramble(k, s1, s2 + n - k) && isScramble(n - k, s1 + k, s2)) ) {34 return hash[make_tuple(n, s1, s2)] = true;35 }36 }37 38 return hash[make_tuple(n, s1, s2)] = false;39 }40 41};42