<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, str1: str, str2: str) -> str:
        """
        - Can we find the shortest string from i,j onwards?

            c    a    b
          
        a   5    4    4  4
        b   5    4    3  3
        a   4    3    3  2
        c   3    3    2  1
            3    2    1  0


           b  b  a  b  a  c  c  c
        b                          8
        c                          7
        a                          6
        c                          5
        a                          4 
        a                          3
        a  8  7  6  6  6  5  4  3  2
        b  8  7  6  5  5  4  3  2  1
           8  7  6  5  4  3  2  1  0
        """
        if len(str1) == 0:
            if len(str2) == 0:
                return ""
            return str2
        elif len(str2) == 0:
            return str1

        dp = [[0] * (len(str2) + 1) for _ in range(len(str1) + 1)]
        for i, row in enumerate(dp):
            row[-1] = len(str1) - i
        for i in range(len(dp[0])):
            dp[-1][i] = len(str2) - i

        for i in range(len(str1) - 1, -1, -1):
            for j in range(len(str2) - 1, -1, -1):
                if str1[i] == str2[j]:
                    dp[i][j] = 1 + dp[i+1][j+1]
                else:
                    dp[i][j] = 1 + min(dp[i+1][j],dp[i][j+1])

        # top_row = ["   "]
        # for char in str2:
        #     top_row.append(char.ljust(3))
        # print("  ".join(top_row))
        # for i,row in enumerate(dp):
        #     r = ["   "]
        #     if i < len(str1):
        #         r = [str1[i].ljust(3)]
        #     for num in row:
        #         r.append(str(num).ljust(3))
        #     print("  ".join(r))

        # bba caa aba ccc

        def backtrack(i: int, j: int, curr: List[int]):
            res = None

            if len(curr) + dp[i][j] > dp[0][0]:
                return None
            elif i == len(str1) and j == len(str2):
                return curr
            elif i == len(str1):
                for k in range(j, len(str2)):
                    curr.append(str2[k])
                return curr
            elif j == len(str2):
                for k in range(i, len(str1)):
                    curr.append(str1[k])
                return curr
            elif str1[i] == str2[j]:
                curr.append(str2[j])
                res = backtrack(i+1,j+1,curr)
                if res is not None:
                    return res
                curr.pop()
            else:
                curr.append(str1[i])
                res = backtrack(i+1,j,curr)
                if res is not None:
                    return res
                curr.pop()

                curr.append(str2[j])
                res = backtrack(i,j+1,curr)
                if res is not None:
                    return res
                curr.pop()

        return backtrack(0,0,[])


    def shortestCommonSupersequenceBk(self, str1: str, str2: str) -> str:
        if len(str1) == 0:
            if len(str2) == 0:
                return ""
            return str2
        elif len(str2) == 0:
            return str1

        seen: Set[tuple[int,int,int]] = set()
        min_res = str1 + str2

        def backtrack(i: int, j: int, curr: List[int]):
            nonlocal min_res

            cache_key = (i,j,len(curr))
            if len(str1) == i and len(str2) == j:
                if len(curr) < len(min_res):
                    min_res = curr.copy()
                return
            elif cache_key in seen:
                return

            seen.add(cache_key)

            if len(str1) == i:
                if len(curr) + len(str2) - j < len(min_res):
                    cp = curr.copy()
                    for k in range(j, len(str2)):
                        cp.append(str2[k])
                    min_res = cp
                return
            elif len(str2) == j:
                if len(curr) + len(str1) - i < len(min_res):
                    cp = curr.copy()
                    for k in range(i, len(str1)):
                        cp.append(str1[k])
                    min_res = cp
                return
            elif str1[i] == str2[j]:
                curr.append(str1[i])
                backtrack(i+1,j+1,curr)
                curr.pop()
            else:
                curr.append(str1[i])
                backtrack(i+1,j,curr)
                curr.pop()

                curr.append(str2[j])
                backtrack(i,j+1,curr)
                curr.pop()

        backtrack(0,0,[])
        return min_res

    def shortestCommonSupersequenceDFS(self, str1: str, str2: str) -> str:
        """
        - When constructing a string, at char k = s1_idx + s2_idx + 1, can either:
            - Add char s1_idx, increment s1_idx
            - Add char s2_idx, increment s2_idx
            - if s1[s1_idx] == s2[s2_idx], add and increment both

        Top-down: O(len(str1) * len(str2)) CC & MC
        - init cache dict of form (i,j) = min_length_str from there
        - dfs helper taking s1_idx, s2_idx, curr
            - if len(curr) == len(s1) + len(s2):
                - return ""
            - if (i,j) in cache, return cache
            - if i == len(s1):
                - cache[(i,j)] = s2[s2_idx]
            - elif j == len(s2):
                - cache[(i,j)] = s1[s1_idx]
            - elif s1[i] == s2[j]:
                - cache[(i,j)] = s1[i] + dfs(i+1,j+1)
            - else
                - cache[(i,j)] = min length of s1 + dfs inc s1, s2 + dfs inc s2
            - return  cache[(i,j)]
        - Return dfs(0,0)
        """
        cache: dict[tuple[int,int], str] = {}
        s1,s2 = str1, str2

        def dfs(s1_idx: int, s2_idx: int):
            cache_key = (s1_idx, s2_idx)
            if len(s1) == s1_idx and len(s2) == s2_idx:
                return ""
            elif cache_key in cache:
                return cache[cache_key]
            elif len(s1) == s1_idx:
                cache[cache_key] = s2[s2_idx:]
            elif len(s2) == s2_idx:
                cache[cache_key] = s1[s1_idx:]
            elif s1[s1_idx] == s2[s2_idx]:
                cache[cache_key] = s1[s1_idx] + dfs(s1_idx+1, s2_idx+1)
            else:
                cache[cache_key] = s1[s1_idx] + dfs(s1_idx + 1, s2_idx)
                s2_res = s2[s2_idx] + dfs(s1_idx, s2_idx + 1)
                if len(s2_res) < len(cache[cache_key]):
                    cache[cache_key] = s2_res

            return cache[cache_key]

        return dfs(0,0)
122691