<p>Given an array of strings <code>words</code>, return <em>the smallest string that contains each string in</em> <code>words</code> <em>as a substring</em>. If there are multiple valid strings of the smallest length, return <strong>any of them</strong>.</p>

<p>You may assume that no string in <code>words</code> is a substring of another string in <code>words</code>.</p>

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

<pre>
<strong>Input:</strong> words = [&quot;alex&quot;,&quot;loves&quot;,&quot;leetcode&quot;]
<strong>Output:</strong> &quot;alexlovesleetcode&quot;
<strong>Explanation:</strong> All permutations of &quot;alex&quot;,&quot;loves&quot;,&quot;leetcode&quot; would also be accepted.
</pre>

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

<pre>
<strong>Input:</strong> words = [&quot;catg&quot;,&quot;ctaagt&quot;,&quot;gcta&quot;,&quot;ttca&quot;,&quot;atgcatc&quot;]
<strong>Output:</strong> &quot;gctaagttcatgcatc&quot;
</pre>

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

<ul>
	<li><code>1 &lt;= words.length &lt;= 12</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 20</code></li>
	<li><code>words[i]</code> consists of lowercase English letters.</li>
	<li>All the strings of <code>words</code> are <strong>unique</strong>.</li>
</ul>

class Solution:
    def shortestSuperstring(self, words: List[str]) -> str:
        def helper(i,j):
            l=0
            left=""
            right=""
            res=0
            while l<min(len(words[i]),len(words[j])): 
                left=words[i][-l-1]+left
                right+=words[j][l]
                l+=1
                if left==right: res=max(res,l)
            return words[j][res:]
        n=len(words)
        pre=[["" for j in range(n)] for i in range(n)]
        for i in range(n-1):
            for j in range(i+1,n):
                pre[i][j]=helper(i,j)
                pre[j][i]=helper(j,i)
        # print(*pre,sep='\n')
        dp=[["" for j in range(1<<n)] for i in range(n)]
        def solve(i,mask):
            if mask==0: return ""
            if dp[i][mask]!="": return dp[i][mask]
            res=""
            for j in range(n):
                if mask&(1<<j):
                    new=pre[i][j]+solve(j,mask^(1<<j))
                    res=new if not res or len(new)<len(res) else res
            dp[i][mask]=res
            # dp[i][mask]=min((pre[i][j]+solve(j,mask^(1<<j)) for j in range(n) if mask&(1<<j)),key=len)
            return dp[i][mask]
        res=""
        for i in range(n):
            new=words[i]+solve(i,((1<<n)-1)^(1<<i))
            res=new if not res or len(new)<len(res) else res
        return res
        # return min((words[i]+solve(i,((1<<n)-1)^(1<<i)) for i in range(n)),key=len)

38500