Why my c++ implementation for finding Longest Common Subsequence gives time limit error on LeetCode. How can I improve the time complexity of this algorithm?
int longestCommonSubsequence(string text1, string text2) {
int n1 = text1.length(), n2 = text2.length();
vector<vector<int>> dp(n1+1, vector<int>(n2+1, -1));
longestCommonSubsequence(text1, text2, n1, n2, dp);
return dp[n1][n2];
}
int longestCommonSubsequence(string text1, string text2, int n1, int n2,
vector<vector<int>> &dp) {
if(n1==0 || n2==0) {
return 0;
}
if(dp[n1][n2] != -1) {
return dp[n1][n2];
}
if(text1[n1-1]==text2[n2-1]) {
dp[n1][n2] = 1 + longestCommonSubsequence(text1, text2, n1-1, n2-1, dp);
return dp[n1][n2];
}
else {
dp[n1][n2] = max(longestCommonSubsequence(text1, text2, n1-1, n2, dp),
longestCommonSubsequence(text1, text2, n1, n2-1, dp));
return dp[n1][n2];
}
}
text1andtext2by const reference instead of by value