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

题目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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值