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
-
DP Table Construction:
- Create a 2D array
dpwheredp[i][j]represents the length of the LCS of the firsticharacters of strings1and the firstjcharacters of strings2. - Recurrence Relation:
- If
s1[i-1] == s2[j-1](since strings are 0-indexed, but the DP table is 1-indexed), thendp[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 ofs1ors2).
- If
- Base Cases:
dp[0][j] = 0anddp[i][0] = 0(LCS of an empty string with any string is 0).
- Create a 2D array
-
Reconstruct the LCS:
- Start from
dp[m][n](wheremandnare lengths ofs1ands2). - 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.
- Start from
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.

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