zoukankan      html  css  js  c++  java
  • [DP]最长公共子序列

    #include <iostream>
    #include <vector>
    #include <string>
    using namespace std;
    
    //最长公共子序列
    vector<vector<int> > getdp1(string str1, string str2) {
        vector<vector<int> > dp(str1.length(), vector<int>(str2.length()));
        if (str1.length() == 0 || str2.length() == 0)
            return dp;
        dp[0][0] = str1[0] == str2[0] ? 1 : 0;
        for (int j = 1; j < str2.length(); j ++)  // 为第一行赋值
            dp[0][j] = max(dp[0][j - 1], str1[0] == str2[j] ? 1 : 0);
    
        for (int i = 1; i < str1.length(); i ++) //为第一列赋值
            dp[i][0] = max(dp[i - 1][0], str2[0] == str1[i] ? 1 : 0);
    
        for (int i = 1; i < str1.length(); i ++) { //滚动求dp矩阵
            for (int j = 1; j < str2.length(); j ++) {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                if (str1[i] == str2[j])
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
            }
        }
        return dp;
    }
    
    string lcse(string str1, string str2) {
        string res = "";
        if (str1.length() == 0 || str2.length() == 0)
            return res;
    
        vector<vector<int> > dp = getdp1(str1, str2);
        int m = str1.length() - 1;
        int n = str2.length() - 1;
        for (m, n; m >= 0 && n >= 0; ) {
                if (m > 0 &&dp[m][n]  == dp[m - 1][n])
                    m --;
                else if (n > 0 && dp[m][n] == dp[m][n - 1])
                    n --;
                else {
                    res = str1[m] + res;
                    m --;
                    n --;
                }
    
        }
        return res;
    }
    
    int main()
    {
        string str1 = "1A2C3D4B56";
        string str2 = "B1D23CA45B6A";
        vector<vector<int> > dp =  getdp1(str1, str2);
        for (int i = 0; i < dp.size(); i ++) {
            for (int j = 0; j < dp[0].size(); j ++)
                cout<<dp[i][j]<<" ";
            cout<<endl;
        }
    
        cout<<lcse(str1, str2)<<endl; //输出12C4B6
    
        return 0;
    }
    
  • 相关阅读:
    C# winform 选择文件保存路径
    笔记
    Redis 队列好处
    异步线程
    WebApi 运行原理
    MVC ---- 怎删改查
    如何快速掌握一门新技术/语言/框架...
    膝盖中了一箭之康复篇
    翻译-Salt与Ansible全方位比较
    膝盖中了一箭之手术篇
  • 原文地址:https://www.cnblogs.com/mooba/p/7473550.html
Copyright © 2011-2022 走看看