LeetCode 1143 Longest Common Subsequence

Tag: 动态规划问题 LeetCode Posted on 2022-02-16 13:51:43 Edited on 2022-02-16 14:46:24 Views: 155

概述

https://leetcode.com/problems/longest-common-subsequence/

动态规划法

极值问题,无脑动态规划。

class Solution {
public:
    vector<vector<int>> dp;
    string text1;
    string text2;
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>> dp(text1.size(), vector<int>(text2.size(), -1));
        this->dp = dp;
        this->text1 = text1;
        this->text2 = text2;
        return helper(0, 0);
    }
    
    int helper(int i, int j) {
        if (i >= text1.size() || j >= text2.size()) return 0;
        if (dp[i][j] != -1) return dp[i][j];
        if (text1[i] == text2[j]) {
            dp[i][j] = 1 + helper(i+1, j+1);
        } else {
            dp[i][j] = max(helper(i+1, j), helper(i, j+1));
        }
        return dp[i][j];
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/