题目:
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Clarification
What's the definition of Longest Common Subsequence?
Example
For "ABCD"
and "EDCA"
, the LCS is "A"
(or "D"
, "C"
), return 1
.
For "ABCD"
and "EACB"
, the LCS is "AC"
, return 2
.
题解:
Solution 1 ()
class Solution {
public:
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
int longestCommonSubsequence(string A, string B) {
int n1 = A.size(), n2 = B.size();
vector<vector<int>> dp(n1 + , vector<int> (n2 + , ));
for (int i = ; i <= n1; ++i) {
for (int j = ; j <= n2; ++j) {
if (A[i - ] == B[j - ]) {
dp[i][j] = dp[i - ][j - ] + ;
} else {
dp[i][j] = max(dp[i - ][j], dp[i][j - ]);
}
}
}
return dp[n1][n2];
}
};