0%

### 题目描述

We can scramble a string s to get a string t using the following algorithm:

1. If the length of the string is 1, stop.
2. If the length of the string is > 1, do the following:
• Split the string into 2 non-empty substrings at a random index, i.e. if the string is `s`, divide it to `x` and y where `s = x + y`.
• Randomly, decide to swap the two substrings or to keep them in the same order. i.e. after this step, `s` may become `s = x + y` or `s = y + x`.
• Apply step 1 recursively on each of the two substrings `x` and `y`.

Given two strings `s1` and `s2` of the same length, return true if `s2` is a scrambled string of `s1`, otherwise, return false.

### 例子

#### 例子 1

Input: s1 = “great”, s2 = “rgeat”
Output: true
Explanation:One possible scenario applied on s1 is:
“great” —> “gr/eat” // divide at random index.
“gr/eat” —> “gr/eat” // random decision is not to swap the two substrings and keep them in order.
“gr/eat” —> “g/r / e/at” // apply the same algorith recursively on both substrings. divide at ranom index each of them.
“g/r / e/at” —> “r/g / e/at” // random decision was to swap the first substing and to keep the second substring in the same order.
“r/g / e/at” —> “r/g / e/ a/t” // again apply the algorithm recursively, divide “at” to “a/t”.
“r/g / e/ a/t” —> “r/g / e/ a/t” // random decision is to keep both substings in the same order.
The algorithm stops now and the result string is “rgeat” which is s2.
As there is one possible scenario that led s1 to be scrambled to s2, we return true.

#### 例子 2

Input: s1 = “abcde”, s2 = “caebd”
Output: false

#### 例子 3

Input: s1 = “a”, s2 = “a”
Output: true

### Constraints

• `s1.length == s2.length`
• `1 <= s1.length <= 30`
• `s1` and `s2` consist of lower-case English letters.

### 解题思路

#### 记忆化 + 递归搜索

1. 初始化一个二维哈希表 `record`，记录每一个 `s1``s2` 的匹配结果
2. 如果 `record[s1][s2]` 存在，直接返回对应结果 （剪枝 1
3. 当给定 `s1``s2` 长度为 1，直接返回 `s1 == s2`
4. `s1 == s2`，返回 `true`
5. 利用哈希表统计 `s1``s2` 的字符频率是否一致，如果不一致直接返回 `false` (剪枝 2，这一步可以减少很多分支)
6. 长度从 `1``s1.length() - 1`，依次分割 s1 为前后两部分（`s1_1, s1_2`）：（以下对 `s2` 的子串均是根据对应 `s1` 的长度来分割，不改变顺序）
• a. 递归调用 `Sramble(s1_1, s2_1)` 记录其结果在 `record[s1_1][s2_1]`，如果 `record[s1_1][s2_1] == false` 跳过 b （剪枝 3
• b. 递归调用 `Sramble(s1_2, s2_2)` 记录在 `record[s1_2][s2_2]`, 如果 `record[s1_2][s2_2] == true` 返回 `true` 重新进入 5 （剪枝 4
• c. 重复 a, b 步骤，不过将 `s1_1``s1_2` 调换前后顺序
7. 当上述循环结束均没有返回时，返回 `false`

• 时间复杂度: O(2^n)? 不确定
• 空间复杂度: O(n^4) 二维哈希表所需空间