<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 get_cost(self, copy_set, prev_vertex, dp):
        copy_set.remove(prev_vertex)
        cost = dp[(prev_vertex, frozenset(copy_set))]
        copy_set.add(prev_vertex)
        return cost

    def get_all_combination(self, vertices):
        output = [set()]
        for vertex in vertices:
            for i in range(len(output)):
                current_set = set(output[i])
                current_set.add(vertex)
                output.append(current_set)

        return sorted(output, key=lambda x: len(x))

    def concatenate(self, a, b):
        if len(b) == 1:
            if a.endswith(b):
                return ""
            else:
                return b
        offset = 0
        for i in range(len(b)):
            if a.endswith(b[:i]):
                offset = i
        return b[offset:]

    def print_tour(self, parent, vertices, start, dp):
        _set = set()
        for vertex in vertices:
            _set.add(vertex)

        stack = []
        while True:
            stack.append(start)
            _set.remove(start)
            start = parent.get((start, frozenset(_set)), None)
            if not start:
                break

        path = stack[0]
        stack = stack[1:]
        for i in stack[::-1]:
            path += self.concatenate(path, i)

        return path

    def problem(self, start, words):
        dp = {}
        parent = {}
        vertices = []
        for word in words:
            if word != start:
                vertices.append(word)

        combinations = self.get_all_combination(vertices)

        for combination in combinations:
            for current_vertex in vertices:
                if current_vertex in combination:
                    continue
                min_cost = math.inf
                min_prev_vertex = 0

                copy_set = set(combination)
                for prev_vertex in combination:
                    cost = self.distance[(prev_vertex, current_vertex)] + self.get_cost(copy_set, prev_vertex, dp)
                    if cost <= min_cost:
                        min_cost = cost
                        min_prev_vertex = prev_vertex

                if len(combination) == 0:
                    min_cost = self.distance[(start, current_vertex)]
                dp[(current_vertex, frozenset(combination))] = min_cost
                parent[(current_vertex, frozenset(combination))] = min_prev_vertex

        _set = set()
        for vertex in vertices:
            _set.add(vertex)

        vertices.append(start)
        _min = math.inf
        prevVertex = -1
        copySet = set(_set)
        for k in _set:
            cost = self.get_cost(copySet, k, dp)
            if cost < _min:
                _min = cost
                prevVertex = k

        parent[(start, frozenset(_set))] = prevVertex

        return self.print_tour(parent, vertices, start, dp)

    def calc(self, a, b):
        for k in range(min(len(a), len(b)), 0, -1):
            if b.startswith(a[-k:]):
                return len(b[k:])
        return len(b)

    def shortestSuperstring(self, words: List[str]) -> str:
        if len(words) == 1:
            return words[0]
        self.distance = {}

        for i in words:
            for j in words:
                self.distance[(i, j)] = self.calc(i, j)
                self.distance[(j, i)] = self.calc(j, i)
        output = []
        for idx, v in enumerate(words):
            output.append(self.problem(v, words=words[:idx] + words[idx + 1:]))

        output = sorted(output, key=lambda x: len(x))
        return output[0]
29800