77. Longest Common Subsequence
Tag:
Dynamic Problem
Main Idea:
DP-Match Problem. As there are two strings s1, s2, let n be the length of s1, m be the length of s2. For the problem, 0 <= i < n, 0 <= j < m.
-
State:
- dp[i][j]: the max LCS for the first i of s1 between first j of s2.
-
Update Function:
- IF s1[i] == s2[j], then dp[i][j] = 1 + dp[i-1][j-1]; ELSE, dp[i][j] = max(dp[i-1][j], dp[i][j-1])
-
Initialization:
- dp[i][0] =0
- dp[0][j] =0
-
Answer:
dp[n][m]
Tips/Notes:
- IF s1[i] == s2[j], then dp[i][j] = 1 + dp[i-1][j-1]. Why not dp[i][j] = 1 + max( dp[i-1][j-1], dp[i][j-1], dp[i-1][j]).
Time/Space Cost:
Time Cost:
Space Cost:
Code:
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
int n = A.length();
int m = B.length();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for(int i = 0; i <= n; i++){
dp[i][0] = 0;
}
for(int j = 0; j <= m; j++){
dp[0][m] = 0;
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(A[i-1] == B[j-1]){
dp[i][j] = 1 + dp[i-1][j-1];
}
else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n][m];
}
};