-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2901.cpp
More file actions
42 lines (41 loc) · 1.29 KB
/
2901.cpp
File metadata and controls
42 lines (41 loc) · 1.29 KB
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
class Solution {
public:
int distance(string& w1, string& w2) {
int m = w1.size();
int cnt = 0;
for (int i = 0; i < m; ++i) {
if (w1[i] != w2[i]) cnt++;
}
return cnt;
}
vector<string> getWordsInLongestSubsequence(vector<string>& words, vector<int>& groups) {
int n = words.size();
vector<int> dp(n, 1);
vector<int> trace(n, -1);
int res = 1;
int maxIndex = 0;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
// check if words[i] can be previous to words[j]
if (words[i].size() != words[j].size()) continue;
if (groups[i] == groups[j]) continue;
if (distance(words[i], words[j]) != 1) continue;
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
trace[i] = j;
if (dp[i] > res) {
res = dp[i];
maxIndex = i;
}
}
}
}
vector<string> v;
while (maxIndex != -1) {
v.push_back(words[maxIndex]);
maxIndex = trace[maxIndex];
}
reverse(v.begin(), v.end());
return v;
}
};