LeetCode Day 53 Dynamic Programming (14/17)
Published:
Continuing to practice with subsequences questions with dp!
Question 1
1143. Longest Common Subsequence
Given two strings
text1andtext2, return the length of their longest common subsequence. If there is no common subsequence, return0.A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
- For example,
"ace"is a subsequence of"abcde".A common subsequence of two strings is a subsequence that is common to both strings.
The difference between this question and Dynamic Programming: LC 718 is that here it is not required to be continuous, but the rest of the ideas are the same
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
for i in range(1, len(text1) + 1):
for j in range(1, len(text2) + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[len(text1)][len(text2)]
Question 2
You are given two integer arrays
nums1andnums2. We write the integers ofnums1andnums2(in the order they are given) on two separate horizontal lines.We may draw connecting lines: a straight line connecting two numbers
nums1[i]andnums2[j]such that:
nums1[i] == nums2[j], and- the line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
Return the maximum number of connecting lines we can draw in this way.
Straight lines cannot intersect, which means that if you find a subsequence of string A that is the same as string B, and this subsequence does not change the relative order, as long as the relative order does not change, the lines linking the same numbers will not intersect.
The question says to find the maximum number of lines drawn, in fact, is to find the length of the longest common subsequence of the two strings!
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
dp = [[0] * (len(B)+1) for _ in range(len(A)+1)]
for i in range(1, len(A)+1):
for j in range(1, len(B)+1):
if A[i-1] == B[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
