簡體   English   中英

最長公共子序列記憶方法在 LeetCode 上給出時間限制誤差

[英]Longest Common Subsequence memoization method gives Time Limit Error on LeetCode

為什么我的用於查找Longest Common Subsequence序列的 C++ 實現在 LeetCode 上給出了time limit error 如何提高該算法的時間復雜度?

    int longestCommonSubsequence(string text1, string text2) {
        int n1 = text1.length(), n2 = text2.length();
        vector<vector<int>> dp(n1+1, vector<int>(n2+1, -1));
        longestCommonSubsequence(text1, text2, n1, n2, dp);
        return dp[n1][n2];
    }
    int longestCommonSubsequence(string text1, string text2, int n1, int n2, 
                                  vector<vector<int>> &dp) {
        if(n1==0 || n2==0) {
            return 0;
        }
        
        if(dp[n1][n2] != -1) {
            return dp[n1][n2];
        }
        
        if(text1[n1-1]==text2[n2-1]) {
            dp[n1][n2] = 1 + longestCommonSubsequence(text1, text2, n1-1, n2-1, dp);
            return dp[n1][n2];
        }
        else {
            dp[n1][n2] = max(longestCommonSubsequence(text1, text2, n1-1, n2, dp), 
                       longestCommonSubsequence(text1, text2, n1, n2-1, dp));
            return dp[n1][n2];
        }
    }

我們可以不用遞歸解決問題,類似使用動態規划。 如果沒有 TLE,這將通過:

// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
#include <vector>
#include <algorithm>

using ValueType = std::uint_fast16_t;

static const struct Solution {
    static const int longestCommonSubsequence(
        const std::string& text_a,
        const std::string& text_b
    ) {
        const ValueType a_len = std::size(text_a);
        const ValueType b_len = std::size(text_b);
        std::vector<std::vector<ValueType>> dp(a_len + 1, std::vector<ValueType>(b_len + 1));

        for (ValueType a = 1; a <= a_len; ++a) {
            for (ValueType b = 1; b <= b_len; ++b) {
                if (text_a[a - 1] == text_b[b - 1]) {
                    dp[a][b] = 1 + dp[a - 1][b - 1];

                } else {
                    dp[a][b] = std::max(dp[a - 1][b], dp[a][b - 1]);
                }
            }
        }

        return dp[a_len][b_len];
    }
};

發送 text1 和 text2 作為引用,因為如果我們按值傳遞它,對於每次遞歸調用,都會創建一個字符串的副本,這對於每次遞歸調用來說都是額外的 O(string_length) 開銷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM