算法珠玑——动态规划(1035)


https://leetcode-cn.com/problems/uncrossed-lines/submissions/

算法珠玑——动态规划(1035)

这道题很有意思!问了这么多,本质上是在求LCS。

class Solution {
public:
    int maxUncrossedLines(vector<int>& A, vector<int>& B) {
        int m = A.size();
        int n = B.size();
        short** dp = new short*[m+1];
        for(int i = 0; i <= m; ++i) dp[i] = new short[n+1]{0};

        for(int i = 1; i <= m; ++i)
            for (int j = 1; j <= n; ++j)
                if(A[i-1] != B[j-1]) dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
                else dp[i][j] = dp[i-1][j-1]+1;

        return dp[m][n];
    }
};

在声明大量数组时,可能会产生性能问题,因此这里将传统的int数组改为short

posted @ 2022-04-05 16:07  千心  阅读(26)  评论(0编辑  收藏  举报