LintCode Longest Common Subsequence(最长公共子序列长度,动态规划入门题)

来源:互联网 发布:知乎 性观念 编辑:程序博客网 时间:2024/05/01 08:31

题目Link:http://www.lintcode.com/en/problem/longest-common-subsequence/

递推公式:
这里写图片描述

#include <iostream>#include <cstring>using namespace std;class Solution {public:    /**     * @param A, B: Two strings.     * @return: The length of longest common subsequence of A and B.     */    int longestCommonSubsequence(string A, string B) {        // write your code here        //得出两个字符串的长度,如果长度为0直接返回0        int lenA = A.length();        int lenB = B.length();        if(lenA == 0 && lenA == lenB)            return 0;        //再字符串头添加空位,方便之后编码从1开始        A = " " + A;        B = " " + B;        int chess[lenA + 1][lenB + 1];        //将表中所有元素置为0        memset(chess, 0, sizeof(int) * lenA * lenB);        for (int i = 1; i <= lenA; i++) {            for (int j = 1; j <= lenB; j++) {                //当两个字符串中 A[i] == A[j],                // 则最长LCS = LCS{(A[i - 1], A[j- 1])} + 1                //否则就在LCS{(A[i - 1], A[j])},和 LCS{(A[i], A[j- 1])}中选最长的那个                //这里的A[i],A[j]均指的是字符串                if (A[i] == B[j]) {                    chess[i][j] = chess[i - 1][j - 1] + 1;                } else {                    chess[i][j] = max(chess[i - 1][j], chess[i][j - 1]);                }            }        }        return chess[lenA][lenB];    }};int main() {    Solution slo;    string str1 = "";    string str2 = "";    cout << slo.longestCommonSubsequence(str1, str2) << endl;    return 0;}

以上是AC代码,至于怎么得到最长公共子序列,可以从chess[lenA][lenB]开始回溯(Traceback),得到LCS。

阅读全文
0 0
原创粉丝点击