题目: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.
思路:
第一个方法是递归,第二个是动态规划。
首先是递归,就是分成两半,其实本题我现在还对scramble string本身的意思不够了解,但是有一些理解了,s1的字符串分解的次序不变,只是s2分解可能从前面也可能从后面开始计算,在定义isScramble函数中,从某一个j的位置分开来的话,有如下两种:
s1[0..j] s1[j+1...n]
s2[0..j] s2[j+1...n]
s2[0..n-j] s2[n-j+1...n] 正是在这样的基础上进行判断,对比程序不难发现其中奥妙之处。
其次是动态规划,难处在于这个是三维数组。
同样,那个第一维表示多少个数,后面的 i,j 表示在数组中的起点位置,至于在每一个循环里面,再设立一个循环,由1到长度大小,就和上面的递归判断的方法一样,不再赘述。
最后返回的是dp[len][0][0]。
代码:
class Solution { public: /* bool isScramble(string s1, string s2) { if(s1.size()!=s2.size()||s1.size()==0||s2.size()==0) return false; if(s1==s2) return true; string ss1=s1,ss2=s2; sort(ss1.begin(),ss1.end()); sort(ss2.begin(),ss2.end()); if(ss1!=ss2) return false; //s1[0..j] s1[j+1...n] //s2[0..j] s2[j+1...n] //s2刚刚是从前面分成两半前面是j个,现在从后面往前分,后面是j个 //isScramble(s1[0..j],s2[0..j])&&isScramble(s1[j+1...n],s2[j+1...n]) //isScramble(s1[0..j],s2[j+1...n])&&isScramble(s1[j+1...n],s2[0..j]) for(int i=1;i<s1.size();i++){ if( isScramble(s1.substr(0,i),s2.substr(0,i)) && isScramble(s1.substr(i,s1.size()-i),s2.substr(i,s1.size()-i)) ) return true; if( isScramble(s1.substr(0,i), s2.substr(s2.size()-i,i)) && isScramble(s1.substr(i, s1.size()-i), s2.substr(0, s2.size()-i)) ) return true; } return false; }*/ bool isScramble(string s1, string s2){ //dp[k][i][j] --> s1[i..i+k-1]与s2[i..i+k-1] //initialization //dp[1][i][j] --> (s1[i]==s2[j])?true:false //dp[k][i][j] = dp[divk][i][j]&&dp[k-divk][i+divk][j+divk] // || dp[divk][i][j+k-divk]&&dp[k-divk][i+divk][j] //牢牢谨记 指的是从i到j个k个字符,既然可以从前面divk个分,也能从后面divk分开 //他仅仅是从i开始k个字符是否能够匹配,只管这么多。 //这是动态规划解法 if(s1.size()!=s2.size()||s1.size()==0||s2.size()==0) return false; if(s1==s2) return true; const int len=s1.size(); vector< vector<vector<bool> > >dp(len+1,vector<vector<bool> >(len,vector<bool >(len))); for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ dp[1][i][j]=(s1[i]==s2[j]); } } for(int k=2;k<=len;k++){ for(int i=0;i<=len-k;i++){ for(int j=0;j<=len-k;j++){ dp[k][i][j]=false; for(int divk=1;divk<k&&dp[k][i][j]==false;divk++){ dp[k][i][j]=(dp[divk][i][j]&&dp[k-divk][i+divk][j+divk])|| (dp[divk][i][j+k-divk]&&dp[k-divk][i+divk][j]); } } } } return dp[len][0][0]; } };