<p>Given two strings <code>str1</code> and <code>str2</code>, return <em>the shortest string that has both </em><code>str1</code><em> and </em><code>str2</code><em> as <strong>subsequences</strong></em>. If there are multiple valid strings, return <strong>any</strong> of them.</p>

<p>A string <code>s</code> is a <strong>subsequence</strong> of string <code>t</code> if deleting some number of characters from <code>t</code> (possibly <code>0</code>) results in the string <code>s</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> str1 = &quot;abac&quot;, str2 = &quot;cab&quot;
<strong>Output:</strong> &quot;cabac&quot;
<strong>Explanation:</strong> 
str1 = &quot;abac&quot; is a subsequence of &quot;cabac&quot; because we can delete the first &quot;c&quot;.
str2 = &quot;cab&quot; is a subsequence of &quot;cabac&quot; because we can delete the last &quot;ac&quot;.
The answer provided is the shortest such string that satisfies these properties.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> str1 = &quot;aaaaaaaa&quot;, str2 = &quot;aaaaaaaa&quot;
<strong>Output:</strong> &quot;aaaaaaaa&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= str1.length, str2.length &lt;= 1000</code></li>
	<li><code>str1</code> and <code>str2</code> consist of lowercase English letters.</li>
</ul>

class Solution:
    def shortestCommonSupersequence(self, s: str, t: str) -> str:
        # dfs(i,j) 返回 s 的前 i 个字母和 t 的前 j 个字母的最短公共超序列的长度
        @cache  # 缓存装饰器，避免重复计算 dfs 的结果
        def dfs(i: int, j: int) -> int:
            if i < 0: return j + 1  # s 是空串，返回剩余的 t 的长度
            if j < 0: return i + 1  # t 是空串，返回剩余的 s 的长度
            if s[i] == t[j]:  # 最短公共超序列一定包含 s[i]
                return dfs(i - 1, j - 1) + 1
            return min(dfs(i - 1, j), dfs(i, j - 1)) + 1

        # make_ans(i,j) 返回 s 的前 i 个字母和 t 的前 j 个字母的最短公共超序列
        # 看上去和 dfs 没啥区别，但是末尾的递归是 if-else
        # make_ans(i-1,j) 和 make_ans(i,j-1) 不会都调用
        # 所以 make_ans 的递归树仅仅是一条链
        def make_ans(i: int, j: int) -> str:
            if i < 0: return t[:j + 1]  # s 是空串，返回剩余的 t
            if j < 0: return s[:i + 1]  # t 是空串，返回剩余的 s
            if s[i] == t[j]:  # 公共超序列一定包含 s[i]
                return make_ans(i - 1, j - 1) + s[i]
            # 如果下面 if 成立，说明上面 dfs 中的 min 取的是 dfs(i - 1, j)
            # 说明 dfs(i - 1, j) 对应的公共超序列更短
            # 那么就在 make_ans(i - 1, j) 的结果后面加上 s[i]
            # 否则说明 dfs(i, j - 1) 对应的公共超序列更短
            # 那么就在 make_ans(i, j - 1) 的结果后面加上 t[j]
            if dfs(i, j) == dfs(i - 1, j) + 1:
                return make_ans(i - 1, j) + s[i]
            return make_ans(i, j - 1) + t[j]

        return make_ans(len(s) - 1, len(t) - 1)

265118