bool search(int n, int i, int j, string s1, string s2) {
if (dp[n][i][j] != -1) {
return dp[n][i][j];
}
if (n == 1) {
return dp[1][i][j] = s1[i] == s2[j];
}
for (int len = 1; len < n; len++) {
bool flag1 = search(len, i, j, s1, s2) && search(n - len, i + len, j + len, s1, s2);
bool flag2 = search(len, i, j + n - len, s1, s2) && search(n - len, i + len, j, s1, s2);
if (flag1 || flag2) {
return dp[n][i][j] = true;
}
}
return dp[n][i][j] = false;
}
vector<vector<vector<int>>> dp;
bool isScramble(string s1, string s2) {
int n = s1.length();
if (n != s2.length()) {
return false;
}
dp = vector<vector<vector<int>>>(n + 1,
vector<vector<int>>(n, vector<int>(n, -1)));
return search(n, 0, 0, s1, s2);
}