### Description

#### LeetCode 87

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*.

**Example 1:**

Input:s1 = "great", s2 = "rgeat"Output:true

**Example 2:**

Input:s1 = "abcde", s2 = "caebd"Output:false

### Analysis

First, we should make the problem clear. The samples are misleading. The partitioning position does not have to be the middle position. It could be any position. So we can’t use divide-and-conquer. A direct method is brutr-force with recursion. The time is \(O(n!)\), which is very large.

However, there is an efficient but difficult to understand method which is based on dynamic programming. If the length of \(s1\) is n, then set a boolean array \(dp[n][n][n]\). The three dimensions are the position of \(s1\), the position of \(s2\) and the length of string that will be compared minus \(1\). So what we will return is \(dp[0][0][n-1]\).

First we could set the value of all the elements whose length of compared string is \(1\). They depend on whether the two elements in \(s1\) and \(s2\) are equal. Then if the length of compared string is larger than \(1\), we must cut the string in each position and judge if the strings that have been cut into are scramble strings. If there is one pair satisfies the scramble string condition, then we could do pruning and return true for this element.

The time of maintaining the array \(dp\) needs \(O(n^3)\). And the cutting process is \(O(n)\). So the time of the method is \(O(n^4)\). And the space is obviously \(O(n^3)\).

### Solution

class Solution { public boolean isScramble(String s1, String s2) { int n=s1.length(); if(n==0) return true; boolean[][][] dp=new boolean[n][n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { dp[i][j][0]=s1.charAt(i)==s2.charAt(j); } } for(int k=1;k<n;k++) { for(int i=0;i<n-k;i++) { for(int j=0;j<n-k;j++) { for(int m=1;m<k+1;m++) { dp[i][j][k]=dp[i][j][k]||dp[i][j][m-1]&&dp[i+m][j+m][k-m]||dp[i][j+k+1-m][m-1]&&dp[i+m][j][k-m]; } } } } return dp[0][0][n-1]; } }

### Reference

[1] https://blog.csdn.net/linhuanmars/article/details/24506703