动规_1143.最长公共子序列

// 状态转移 :
// 1.正常匹配 :dp[i][j] = dp[i - 1][j - 1] + 1;
// 匹配就取左上角的值 + 1
// 2.未匹配 :dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
// 未匹配就取左 / 上 中最大的一个
class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int rows = text1.size();
        int cols = text2.size();
        int dp[rows][cols];
        memset(dp, 0, sizeof(dp));
        // base case
        if (text1[0] == text2[0]) dp[0][0] = 1;
        // 对首列 如果相等记作 1
        for (int i = 1; i < rows; i++) {
            dp[i][0] = dp[i - 1][0];
            if (text1[i] == text2[0]) {
                dp[i][0] = 1;
            }
        }
        // 对首行 如果相等记作 1
        for (int j = 1; j < cols; j++) {
            dp[0][j] = dp[0][j - 1];
            if (text1[0] == text2[j]) {
                dp[0][j] = 1;
            }
        }
        // 状态转移
        for (int i = 1; i < rows; i++)
            for (int j = 1; j < cols; j++) {
                if (text1[i] == text2[j]) { // 匹配
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else { // 不匹配,取较大值
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        return dp[rows - 1][cols - 1];
    }
};
// 状压版本
class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        const int cols = text2.size();
        vector<int> dp(cols, 0);
        // 一次性将text1的当前字符值取出来,避免重复数组操作
        for (const auto ti : text1) {
            int last = dp[0];
            if (ti == text2[0]) {
                dp[0] = 1;
            }

            for (int j = 1; j < cols; j++) {
                if (ti == text2[j]) {
                    swap(dp[j], last);
                    dp[j]++;
                } else {
                    last = dp[j];
                    if (dp[j - 1] > dp[j])
                        dp[j] = dp[j - 1];
                }
            }
        }
        return dp[cols - 1];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值