leetcode_943

Given an array A of strings, find any smallest string that contains each string in A as a substring.

We may assume that no string in A is substring of another string in A.

Example 1:

Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.

Example 2:

Input: ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"

Note:

  • 1 <= A.length <= 12

  • 1 <= A[i].length <= 20

Solutions

  1. dfs O(n!) S(n2)

  2. com is an integer representing strings have been used in the current path.

  1. dynamic programming O(2^n * n2) S(n2)

  2. dp[set][i] represents the maximum overlap with strings in set and the last string is s[i].

  3. It's a Travelling Salesman Problem. ie: Find the shortest path which visits every node extractly once.

  4. Codes below find the permutation with the maximum length of overlaps which is similar to the official answer.

    • These two criterias are basically the same.

  1. dynamic programming with memoization O(2^n * n2) S(2^n + n2)

  2. Got TLE.

Last updated

Was this helpful?