algorithm - 最长公共(public)子串的 DP 内存方法

标签 algorithm dynamic-programming

谁能提供两个字符串之间最长公共(public)子串的内存方法。我知道底部解决方案,但我无法以自上而下的方式思考。 期望时间复杂度-O(n^2)

最佳答案

自上而下的方法

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

string X, Y;             //input strings
int ans, dp[105][105];   // ans : answer

int LCS(int n, int m)    //our function return value of (n,m) state
{                        // so that we can use the result in (n+1,m+1) state
  if(n == 0 || m == 0) return 0;   //in case of match in (n+1,m+1) state
  if(dp[n][m] != -1) return dp[n][m];

  LCS(n-1,m);          //to visit all n*m states          (try example:  X:ASDF
  LCS(n,m-1);          // we call these states first                     Y:ASDFF)

  if(X[n-1] == Y[m-1])
  {

    dp[n][m] =  LCS(n-1,m-1) + 1;
    ans = max(ans, dp[n][m]);
    return dp[n][m];
  }
    return dp[n][m] = 0;
}

int main()
{
    int t; cin>>t;
    while(t--)
    {
      int n, m; cin>>n>>m;  //length of strings
      cin>>X>>Y;
      memset(dp, -1, sizeof dp);
      ans = 0;
      LCS(n, m);
      cout<<ans<<'\n';
    }
    return 0;
}

关于algorithm - 最长公共(public)子串的 DP 内存方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859547/

相关文章:

algorithm - 找到最低票价

algorithm - 您如何找到学生在类里面的最佳分配?

.net - 任何用于医疗诊断和数据挖掘的 .NET 开源项目

c - 查找数组中未出现两次的整数

algorithm - 动态规划要达到一个阈值?

algorithm - 如何改进这个动态规划解决方案?

algorithm - 哪些应用程序/游戏状态 "delta compression"技术/算法确实存在?

java - 欧拉投影数字阶乘之和

php - 从数据库动态填写测验表格(PHP/MySQL)

algorithm - 给定某些限制的座位方式的数量