[LeetCode] Scramble String
Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great"
:
great / \ gr eat / \ / \ g r e at / \ a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr"
and swap its two children, it produces a scrambled string "rgeat"
.
rgeat / \ rg eat / \ / \ r g e at / \ a t
We say that "rgeat"
is a scrambled string of "great"
.
Similarly, if we continue to swap the children of nodes "eat"
and "at"
, it produces a scrambled string "rgtae"
.
rgtae / \ rg tae / \ / \ r g ta e / \ t a
We say that "rgtae"
is a scrambled string of "great"
.
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
可以用递归来解决,用备忘录方法加速。备忘录也就是DP的一种变形了,所以我就直接改为递推式的DP了。O(n^4)
1 class Solution { 2 private: 3 bool f[100][100][100]; 4 public: 5 bool isScramble(string s1, string s2) { 6 // Start typing your C/C++ solution below 7 // DO NOT write int main() function 8 if (s1.size() != s2.size()) 9 return false; 10 11 for(int i = 0; i < s1.size(); i++) 12 for(int j = 0; j < s2.size(); j++) 13 f[1][i][j] = (s1[i] == s2[j]); 14 15 for(int len = 2; len <= s1.size(); len++) 16 { 17 for(int s1Beg = 0; s1Beg < s1.size(); s1Beg++) 18 { 19 int s1End = s1Beg + len - 1; 20 if (s1End >= s1.size()) 21 break; 22 23 for(int s2Beg = 0; s2Beg < s2.size(); s2Beg++) 24 { 25 int s2End = s2Beg + len - 1; 26 if (s2End >= s2.size()) 27 break; 28 29 f[len][s1Beg][s2Beg] = false; 30 for(int s1Mid = s1Beg; s1Mid < s1End; s1Mid++) 31 { 32 int leftSize = s1Mid - s1Beg + 1; 33 int rightSize = len - leftSize; 34 int s2Mid = s2Beg + leftSize - 1; 35 bool res1 = f[leftSize][s1Beg][s2Beg] && f[rightSize][s1Mid+1][s2Mid+1]; 36 37 s2Mid = s2End - leftSize; 38 bool res2 = f[leftSize][s1Beg][s2Mid+1] && f[rightSize][s1Mid+1][s2Beg]; 39 40 f[len][s1Beg][s2Beg] = f[len][s1Beg][s2Beg] || res1 || res2; 41 } 42 } 43 } 44 } 45 46 return f[s1.size()][0][0]; 47 } 48 };