forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortest-common-supersequence.cpp
45 lines (43 loc) · 1.6 KB
/
shortest-common-supersequence.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
// Time: O(m * n)
// Space: O(m * n)
class Solution {
public:
string shortestCommonSupersequence(string str1, string str2) {
vector<vector<int>> dp(2, vector<int>(str2.size() + 1));
vector<vector<tuple<int, int, char>>> bt(str1.size() + 1,
vector<tuple<int, int, char>>(str2.size() + 1));
for (int i = 0; i < str1.length(); ++i) {
bt[i + 1][0] = {i, 0, str1[i]};
}
for (int j = 0; j < str2.length(); ++j) {
bt[0][j + 1] = {0, j, str2[j]};
}
for (int i = 0; i < str1.length(); ++i) {
for (int j = 0; j < str2.length(); ++j) {
if (dp[i % 2][j + 1] > dp[(i + 1) % 2][j]) {
dp[(i + 1) % 2][j + 1] = dp[i % 2][j + 1];
bt[i + 1][j + 1] = {i, j + 1, str1[i]};
} else {
dp[(i + 1) % 2][j + 1] = dp[(i + 1) % 2][j];
bt[i + 1][j + 1] = {i + 1, j, str2[j]};
}
if (str1[i] != str2[j]) {
continue;
}
if (dp[i % 2][j] + 1 > dp[(i + 1) % 2][j + 1]) {
dp[(i + 1) % 2][j + 1] = dp[i % 2][j] + 1;
bt[i + 1][j + 1] = {i, j, str1[i]};
}
}
}
int i = str1.length(), j = str2.length();
char c = 0;
string result;
while (i != 0 || j != 0) {
tie(i, j, c) = bt[i][j];
result.push_back(c);
}
reverse(result.begin(), result.end());
return result;
}
};