1
vector<vector<int>> dp, pre, par;3
bool startWith(string s, string t) {4
// returns true if string s starts with string t6
for (i = 0; i < s.length() && i < t.length(); i++) {18
int calc(string A, string B) {19
// calculate the number of extra characters required to be appended to A20
// if A is followed by B21
// for eg. calc("abcd","cdef") = 223
int a = A.length(), b = B.length();24
for (int i = 0; i < a; i++) {25
if (a - i <= b && startWith(B, A.substr(i))) {34
int helper(int mask, int last) {35
// returns the minimum length of string required if last string appended was36
// A[last] the sets bit in mask represents the strings that were already37
// appended to the final string39
if (mask == finalMask) // all strings are appended in final string42
if (dp[mask][last] != -1) // memoization43
return dp[mask][last];47
for (int i = 0; i < n; i++) {48
if (mask & (1 << i)) continue;49
int cost = pre[last][i] + helper(mask | (1 << i),50
i); // extra characters need to be appended56
par[mask][last] = p; // store parent, so that it is easy to traceback and find58
return dp[mask][last] = mn; // store result in DP table63
string shortestSuperstring(vector<string> &A) {66
vector<int>(n)); // for pre-computing calc(a,b) for all pairs of strings67
par.assign(1 << n, vector<int>(n, -1));68
for (int i = 0; i < n; i++) {69
for (int j = 0; j < n; j++) {71
pre[i][j] = calc(A[i], A[j]);74
finalMask = (1 << n) - 1;75
dp.assign(1 << n, vector<int>(n, -1));76
int len = INT_MAX; // len will contain minimum length of required string78
for (int i = 0; i < n; i++) {80
len = min(len, (int)A[i].length() + helper(1 << i, i));86
// Now traceback to find the final answer92
len = pre[prev_ind][ind];93
int alen = A[ind].length();94
ans += A[ind].substr(alen - len, len);95
msk = msk ^ (1 << ind);