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.
基本思路:
动太规划
两个字符串s1, s2,在合适的地方截成两段。是不是scramble,由以下两种情况组成。
-----******** and -----********
-----******** and ********-----
至于在哪里截断,则进行逐个位置偿试。 这方法很暴力,唯一与暴力不同的地方,就是将过去已经做的运算存储起来,避免了重复运算。
需要一个三维数组来存储中间运算结果。
dp[i][j][len] 存储着, s1串,从第i个位置为起始,长度为len的子串, 和s2串,从第j个位置为起始,长度为len的字串,是否为scramble。
最终目标,要求出dp[0][0][s1.size()]的值。
而为了求出 dp[i][j][len], 需要 逐步偿试,将dp[i][j][len] 所代表的子串,进行逐个子串切分, 即进行从位置 1.. len-1 分别切分偿试。
递推式为
dp[i][j][len-1] |= dp[i][j][k-1] && dp[i+k][j+k][len-k-1];
dp[i][j][len-1] |= dp[i][j+len-k][k-1] && dp[i+k][j][len-k-1];
第二行,对应, 2. -----******** and ********-----
此代码在leetcode上实际运行时间为106ms。
class Solution {
public:
bool isScramble(string s1, string s2) {
if (s1.empty() && s2.empty()) return true;
if (s1.size() != s2.size()) return false;
const int size = s1.size();
vector<vector<vector<char> > > dp(size, vector<vector<char> >(size, vector<char>(size)));
for (int i=s1.size()-1; i>=0; i--) {
for (int j=s2.size()-1; j>=0; j--) {
dp[i][j][0] = s1[i] == s2[j];
for (int len=2; len<=size-i && len<=size-j; len++) {
for (int k=1; k<len; k++) {
dp[i][j][len-1] |= dp[i][j][k-1] && dp[i+k][j+k][len-k-1];
dp[i][j][len-1] |= dp[i][j+len-k][k-1] && dp[i+k][j][len-k-1];
}
}
}
}
return dp[0][0][size-1];
}
};在leetcode上,有代码用时只需要6ms。但是不明白为什么他那样做是对的。
https://leetcode.com/discuss/27889/my-accepted-solution-in-6ms-little-change-in-normal-solution
原文地址:http://blog.csdn.net/elton_xiao/article/details/45222705