参考 https://algorithm.yuanbin.me/zh-hans/dynamic_programming/longest_common_subsequence.html
image.png
状态转移方程:
c[i][j] =
(1) 0 if i == 0 && j == 0
(2) c[i - 1][j - 1] + 1, if A[i] == B[j]
(3) max(c[i][j - 1], c[i - 1][j]) if A[i] != B[j]
class Solution {
public:
/**
* @param A: A string
* @param B: A string
* @return: The length of longest common subsequence of A and B
*/
int longestCommonSubsequence(string &A, string &B) {
// write your code here
if(A.empty()) return 0;
if(B.empty()) return 0;
int lenA = A.size();
int lenB = B.size();
vector<vector<int>> dp(lenA + 1);
for(int i = 0; i < lenA + 1; i++){
dp[i].resize(lenB + 1, 0);
}
for(int i = 1; i < lenA + 1; i++){
for(int j = 1; j < lenB + 1; j++){
if(A[i - 1] == B[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else{
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[lenA][lenB];
}
};
网友评论