递归调用子问题。每次分成子问题处理,注意子问题不能为空。
class Solution {
public:bool isScramble(string s1, string s2) {
const int n1 = s1.size();
const int n2 = s2.size();
if(n1!=n2)return false;
if(n1==0)return true;
return solve(s1,s2);
}
private:
bool solve(const string &s1,const string &s2){
const int n = s1.size();
if(n==1){
return s1[0]==s2[0];
}
int count[128];
memset(count,0,sizeof(count));
for(int i = 0;i<n;i++)count[s1[i]]++;
for(int i = 0;i<n;i++)if(count[s2[i]]==0){
return false;
}else count[s2[i]]--;
string tmp1,tmp2;
string tmp3,tmp4;
string tmp5,tmp6;
for(int i = n-1;i>=0;i--){
tmp2.push_back(s1[i]);
tmp4.push_back(s2[i]);
tmp6.push_back(s2[n-i-1]);
}
for(int i = 1;i<=n-1;i++){
tmp1.push_back(s1[i-1]);
tmp2.pop_back();
tmp3.push_back(s2[i-1]);
tmp4.pop_back();
bool ok = solve(tmp1,tmp3) &solve(tmp2,tmp4);
if(ok)return true;
tmp5.push_back(s2[n-i]);
tmp6.pop_back();
ok = solve(tmp1,tmp5) &solve(tmp2,tmp6);
if(ok)return true;
}
return false;
}
};