博文中会简要介绍Leetcode P0087题目分析及解题思路。
“Scramble String”是一道比较难的动态规划题目,这道题的难点在于寻找最优子结构。这道题最终是一个高维动态规划,寻找最优子结构相对而言比较难,反而是最终的递推式逻辑简单,并不复杂。
We can scramble a string s to get a string t using the following algorithm:
- If the length of the string is 1, stop.
- 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.
这道题的核心思路和递推式写法均以在Java和C++代码中详细注释,这里不再赘述。
以下是Java的题解代码实现。
以下是C++的题解代码实现。