-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-the-shortest-superstring.cpp
70 lines (66 loc) · 2.29 KB
/
find-the-shortest-superstring.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Time: O(n^2 * (l^2 + 2^n))
// Space: O(n^2)
class Solution {
public:
string shortestSuperstring(vector<string>& A) {
const int n = A.size();
vector<vector<int>> overlaps(n, vector<int>(n));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
for (int l = min(A[i].length(), A[j].length());
l >= 0; --l) {
if (A[i].substr(A[i].length() - l) == A[j].substr(0, l)) {
overlaps[i][j] = l;
break;
}
}
}
}
vector<vector<int>> dp(1 << n, vector<int>(n));
vector<vector<int>> prev(1 << n, vector<int>(n, -1));
for (int mask = 1; mask < 1 << n; ++mask) {
for (int bit = 0; bit < n; ++bit) {
if (((mask >> bit) & 1) == 0) {
continue;
}
auto prev_mask = mask ^ (1 << bit);
for (int i = 0; i < n; ++i) {
if (((prev_mask >> i) & 1) == 0) {
continue;
}
auto value = dp[prev_mask][i] + overlaps[i][bit];
if (value > dp[mask][bit]) {
dp[mask][bit] = value;
prev[mask][bit] = i;
}
}
}
}
int bit = -1;
for (int i = 0; i < n; ++i) {
if (bit == -1 ||
dp.back()[i] > dp.back()[bit]) {
bit = i;
}
}
vector<int> words;
for (int mask = (1 << n) - 1; bit != -1;) {
words.emplace_back(bit);
tie(mask, bit) = make_pair(mask ^ (1 << bit),
prev[mask][bit]);
}
reverse(words.begin(), words.end());
unordered_set<int> lookup(words.begin(), words.end());
for (int i = 0; i < n; ++i) {
if (!lookup.count(i)) {
words.emplace_back(i);
}
}
auto result = A[words[0]];
for (int i = 1; i < words.size(); ++i) {
auto overlap = overlaps[words[i - 1]][words[i]];
result += A[words[i]].substr(overlap);
}
return result;
}
};