内容中心

2026年热门的6M63模组端板高口碑品牌推荐-四川鑫佳盛铝业有限公司

To solve the Longest Common Subsequence (LCS) problem using dynamic programming, we follow a bottom-up approach to build a DP table that stores the length of the LCS for substrings of the input strings. We then backtrack from the end of the table to reconstruct the actual LCS string.

Approach

  1. DP Table Construction:

    • Create a 2D array dp where dp[i][j] represents the length of the LCS of the first i characters of string s1 and the first j characters of string s2.
    • Recurrence Relation:
      • If s1[i-1] == s2[j-1] (since strings are 0-indexed, but the DP table is 1-indexed), then dp[i][j] = dp[i-1][j-1] + 1 (add the common character to the LCS of the substrings without these characters).
      • Else, dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (take the maximum LCS length from excluding the current character of s1 or s2).
    • Base Cases: dp[0][j] = 0 and dp[i][0] = 0 (LCS of an empty string with any string is 0).
  2. Reconstruct the LCS:

    • Start from dp[m][n] (where m and n are lengths of s1 and s2).
    • If characters at current positions are the same, add the character to the result and move diagonally up-left.
    • Else, move in the direction of the larger value in the DP table (up or left).
    • Reverse the result to get the correct order of the LCS.

Solution Code

def longest_common_subsequence(s1, s2):
    m = len(s1)
    n = len(s2)

    # Step 1: Build the DP table for LCS length
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i-1] == s2[j-1]:
                dp[i][j] = dp[i-1][j-1] + 1
            else:
                dp[i][j] = max(dp[i-1][j], dp[i][j-1])

    # Step 2: Reconstruct the LCS string
    i, j = m, n
    lcs_str = []
    while i > 0 and j > 0:
        if s1[i-1] == s2[j-1]:
            lcs_str.append(s1[i-1])
            i -= 1
            j -= 1
        elif dp[i-1][j] > dp[i][j-1]:
            i -= 1
        else:
            j -= 1

    return ''.join(reversed(lcs_str)), dp[m][n]

# Example Usage
s1 = "abcde"
s2 = "ace"
lcs_str, lcs_length = longest_common_subsequence(s1, s2)
print(f"LCS String: {lcs_str}")  # Output: ace
print(f"LCS Length: {lcs_length}")  # Output: 3

Explanation

  • DP Table: The table is filled in a bottom-up manner, ensuring that each subproblem is solved before larger problems that depend on it.
  • Reconstruction: By backtracking from the end of the table, we efficiently retrieve the LCS string without recalculating any values.

This approach has a time complexity of O(m*n) (due to filling the DP table) and space complexity of O(m*n) (for the DP table). For space optimization, a 1D array can be used, reducing space to O(min(m,n)). However, the 2D version is easier to understand and reconstruct the LCS.

The solution provides both the LCS string and its length, which are the key outputs for the problem.

四川鑫佳盛铝业有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?