[HackerRank] The Longest Common Subsequence

简介: This is the classic LCS problem. Since it requires you to print one longest common subsequence, just use the O(m*n)-space version here.

This is the classic LCS problem. Since it requires you to print one longest common subsequence, just use the O(m*n)-space version here.

My accepted code is as follows.

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 vector<int> lcs(vector<int>& a, vector<int>& b) {
 8     int n = a.size(), m = b.size();
 9     vector<vector<int> > dp(n + 1, vector<int> (m + 1, 0));
10     for (int i = 1 ;i <= n; i++) {
11         for (int j = 1; j <= m; j++) {
12             if (a[i - 1] == b[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
13             else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
14         }
15     }
16     vector<int> res;
17     for (int i = n, j = m; i >= 1 && j >= 1;) {
18         if (a[i - 1] == b[j - 1]) {
19             res.push_back(a[i - 1]);
20             i--;
21             j--;
22         }
23         else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
24         else j--;
25     }
26     reverse(res.begin(), res.end());
27     return res;
28 }
29 
30 int main() {
31     /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
32     int n, m;
33     while (scanf("%d %d", &n, &m) != EOF) {
34         vector<int> a(n);
35         vector<int> b(m);
36         for (int i = 0; i < n; i++)
37             scanf("%d", &a[i]);
38         for (int i = 0; i < m; i++)
39             scanf("%d", &b[i]);
40         vector<int> res = lcs(a, b);
41         for (int i = 0; i < (int)res.size(); i++)
42             printf("%d ", res[i]);
43         printf("\n");
44     }
45     return 0;
46 }

 Well, try this problem here and get Accepted :)

目录
相关文章
Leetcode 516. Longest Palindromic Subsequence
找到一个字符串的最长回文子序列,这里注意回文子串和回文序列的区别。子序列不要求连续,子串(substring)是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。
49 0
|
6月前
|
人工智能
HDU-1159-Common Subsequence
HDU-1159-Common Subsequence
37 0
|
算法
LeetCode 300. Longest Increasing Subsequence
给定一个无序的整数数组,找到其中最长上升子序列的长度。
54 0
LeetCode 300. Longest Increasing Subsequence
|
索引
Leetcode-Medium 5. Longest Palindromic Substring
Leetcode-Medium 5. Longest Palindromic Substring
116 0
LeetCode之Longest Common Prefix
LeetCode之Longest Common Prefix
107 0