Intuition
This is a dynamic programming problem. Given two string S1(1,2,3,...,n)
and S2(1,2,3,...,n)
, they are scramble if and only if:
S1(1,2,3,...,i) and S2(1,2,3,...,i) are scramble
andS1( i+1,...,n) and S2(i+1,...,n) are scramble
For
abb
andbab
, they can be seperated into two parts:ab
andba
are scramble ,b
andb
are scramble.S1(1,2,3,...,i) and S2(n-i+1,n-i+2,...,n) are scramble
andS1( i+1,...,n) and S2(1,2,...,n-i) are scamble
In the above cases,
ab
andba
are scramble because they can be seperated into two parts,a
andb
,b
anda
, the left part of the first string equals the right part of the second string, the right part of the left equals the left part of the second, they are symmetric.
The termination condition for this recursion solution is two strings are equal.
Algorithm
Recusion
Termination Condition: If two strings are equal, then they are also scramble.
Recursion Process: For S1(1,2,3,...,n)
, S2(1,2,3,...,n)
and a specified substring size i
ranging from 1 to n, we need to split the strings into two parts, and check if the substrings are scramble according to the illustration stated before.
Trick: We can do a precheck before recusion process, it’s much less time consumping than recusion. We can store how many times each character appears in both strings, if they are not equal, these two strings can never be scamble. Say afbihuifafaf
and ghuiigafsafh
, if we donot have this precheck process, we have to compare:
a
andg
,fbihuifafaf
andhuiigafsafh
a
andh
,fbihuifafaf
andghuiigafsaf
af
andgh
,bihuifafaf
anduiigafsafh
…
That’s a huge workload!
Iteration
State Transition: dp[n][n][n+1] is state matrix, dp[i][j][k] denotes if substring S1(i, i+1, ..., i+k-1)
and S2(j, j+1, ..., j+k-1)
are scramble. So dp[0][0][n] is our final answer. According to above analysis, state transition equation should be:1
dp[i][j][k] = (dp[i][j][p] && dp[i+p][j+p][k-p])||(dp[i][j+k-p][p] && dp[i+p][j][k-p]) p={1,2,...,k-1}
Code
Recusion
1 | class Solution { |
Iteration
1 | class Solution { |
Complexity
Recursion
Time Complexity: O(2^n)
*Space Complexity: *O(2^n), See the blog here
Iteration
Time Comlexity: For the iteration solution, it’s easy to figure out the approximate time complexity, since we have four for loop, it costs O(n^4). The accurate analysis is more complicated, you can refer to discussions here or the blog.
Space Complexity: O(n^3), costs for the arraydp[n][n][n+1]