【问题标题】:why am i getting slightly off outputs for this dp problem?为什么我会因为这个 dp 问题而稍微偏离输出?
【发布时间】: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


【解决方案1】:

如果A == [1, 2, 3, 4, 5]B == [1, 2, 4, 5],那么最长的公共序列是2,你的答案是3,但你只需要在B中添加一个数字3就可以满足要求。所以整体逻辑似乎不正确

【讨论】:

  • 两者的LCS将是4而不是2。这是子序列。
  • @Alex 不,答案是 4,因为它应该是一个子序列。
猜你喜欢
  • 2021-04-06
  • 2019-05-09
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
相关资源
最近更新 更多