Description
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"
:
1 | great |
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"
.
1 | rgeat |
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"
.
1 | rgtae |
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.
Example 1:
1 | Input: s1 = "great", s2 = "rgeat" |
Example 2:
1 | Input: s1 = "abcde", s2 = "caebd" |
解法
很明显的一道动态规划的题,先解释一下动态规划的渊源。
一般动态规划可解的题都是分治递归可解的,我们不难发现,分治算法之所以理论复杂度很高,其原因是因为重复的进行了很多子问题的计算,这是不必要的,如果我们一旦计算出某个子问题的结果,就将其存在内存中,下次要用到的时候,我们就直接使用不再次进行计算的话,这样是不是就能够减少很多复杂度呢?
实际上,这样的方法被称作“记忆化”,即将已经发生过的计算的结果记忆下来,以待之后使用。
特别的,由于运算过程中保证小的子问题需要先进行运算,我们可以不用递归来进行这样的计算,而是按照从小到大的顺序依次将所有的子问题计算出来,由于小的子问题先得到计算,所以我们可以确保在计算某一个之后的问题时,它需要的所有子问题都已经得到了计算。
这样的方法,被称作动态规划,这也是为什么常有人说动态规划和记忆化是非常类似的算法的原因了。
在实现中,其实就和分治算法非常类似,不过是将递归的过程改成了递推。
回到题目本身,题目的问题可以这样分析,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22.那么要么s11和s21是scramble的并且s12和s22是scramble的;要么s11和s22是scramble的并且s12和s21是scramble的。
i,j,代表字符串的开始位置,len代表比较的长度,在len内按照长度k进行分割
递归式为:
1 | dp[i][j][len] = || (dp[i][j][k] && dp[i + k][j + k][len - k]) || (dp[i + k][j][len - k] && dp[i][j + len - k][k]) |
具体代码如下:
1 | class Solution { |