<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, A: List[str]) -> str:
        
        def distance(from_str, to_str):
            for i in range(1, len(from_str)):
                #from_str: words, to_str: ordsk
                if to_str.startswith(from_str[i:]):
                    return len(from_str) - i + 1
            return 1
        n = len(A)
        graph = [[1]*n for _ in range(n)]
        for i in range(n):
            for j in range(i, n):             
                graph[i][j] = distance(A[i], A[j])
                graph[j][i] = distance(A[j], A[i])
        
        d = [[0] * n for _ in range(1<<n)]
        
        max_overlap = -1
        max_path = []
        
        final_step = (1 << n) - 1
        #(node, mask, path, overlap)
        queue = deque((i, 1<<i, [i], 0) for i in range(n))
        while queue:
            node, mask, path, overlap = queue.popleft()
            # if this step we get the same overlap, we should still continue because 
            # here we can get 3 1 or 2 1 with the same overlap at 1, but 3 1 2 and 2 1 3 may yield different overlap values. For the cases where 3 4 2 1 and 4 3 2 1 that have the same overlap and mask, and node, one of them should already be exclude by the second exclusion
            if overlap < d[mask][node]:
                print(mask, node)
                continue
            
            if mask == final_step:
                if max_overlap < overlap:
                    max_overlap, max_path = overlap, path
            
            for i in range(n):
                if (1 << i) & mask:
                    continue
                next_mask = mask | 1 << i 
                next_overlap = overlap + graph[node][i]
                if next_overlap > d[next_mask][i]:
                    d[next_mask][i] = next_overlap
                    queue.append((i, next_mask, path + [i], d[next_mask][i]))
        ans = A[max_path[0]]
        for i in range(1, n):
            #words
            #ordsk
            prev = max_path[i-1]
            curr = max_path[i]
            overlap = graph[prev][curr] - 1
            ans += A[curr][overlap:]
            
        return ans        
20800