【发布时间】:2020-08-22 15:17:08
【问题描述】:
问题:
给定一个由 N 个不同整数组成的数组 A 和一个由整数组成的数组 B(不必是不同的)。找到最小号码。需要添加到 B 以使 A 成为它的子序列的数字。
我的策略:
很简单 - 找到最长的公共子序列 lcs,因此答案是 sizeof(A) - lcs。
我的代码:
int lcs(vector<int>A, vector<int>B, int n, int m)
{
int L[m + 1][n + 1];
int i, j;
/* Following steps build L[m+1][n+1] in
bottom up fashion. Note that L[i][j]
contains length of LCS of X[0..i-1]
and Y[0..j-1] */
for (i = 0; i <= m; i++)
{
for (j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (B[i - 1] == A[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
/* L[m][n] contains length of LCS
for A[0..n-1] and B[0..m-1] */
return (n - L[m][n]);
}
我的输出:
我得到错误的输出。 (主要相差 1。)我还获得了一些测试用例的 TLE。
有人能找出我在逻辑或代码中出错的地方吗?
【问题讨论】:
-
你能分享预期的实际 O/p 和输入吗?
标签: c++ c++11 dynamic-programming subsequence