【发布时间】:2020-12-28 14:23:36
【问题描述】:
为什么我的用于查找Longest Common Subsequence 的 c++ 实现在 LeetCode 上给出了time limit error。如何提高该算法的时间复杂度?
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];
}
}
【问题讨论】:
-
不知道是否重要,但您可以通过 const 引用而不是值传递
text1和text2 -
真的需要分配(n1+1)x(n2+1)的矩阵吗? n1xn2 不够吗?另外,我想知道它是否有助于从 n1/2 开始,寻找对数复杂度而不是线性。如果这与记忆化相得益彰,可能值得考虑。
标签: c++ algorithm memoization