Day25-Uncrossed Lines(Medium)
问题描述:
We write the integers of A and B (in the order they are given) on two separate horizontal lines.
Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:
A[i] == B[j];
The line we draw does not intersect any other connecting (non-horizontal) line.
Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.
Return the maximum number of connecting lines we can draw in this way.
从两个给定的数组中找到不相交的连线,所谓连线就是两个数组中值相同的元素连接起来。而我们不能改变数组中元素的顺序,找到总共有多少不相交的连线。
Example:
Example 1:
Input: A = [1,4,2], B = [1,2,4]
Output: 2
Explanation: We can draw 2 uncrossed lines as in the diagram.
We cannot draw 3 uncrossed lines, because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.
Example 2:
Input: A = [2,5,1,2,5], B = [10,5,2,1,5,2]
Output: 3
Example 3:
Input: A = [1,3,7,1,7,5], B = [1,9,2,5,1]
Output: 2
Note:
1 <= A.length <= 500
1 <= B.length <= 500
1 <= A[i], B[i] <= 2000
解法(DP):
心态炸了啊今天,昨天帮导师改了一天的课本,今天想早上找个算法练练手开始一天的工作,没想到又是动态规划的题。。。
找到解析后,写的时候又因为python数组有个浅拷贝的问题死活通过不了。。
不管怎样先说这题吧,动态规划的题真的是给出了解析后感觉好简单的题,但是不给解析又好难想。动态规划老样子先设置一个动态数组,然后我们更新这个数组就行了,这个数组在本题中的含义是什么呢,其实就是每个为止能有多少条不相交的线。比如dp[i][j]就是对应于数组A中i位置和B中j位置之前包括该点所有构成的不相交线的条数。这个值是怎么更新的呢。可以想象如果这个两个点相连的话,这个点的值就是i- 1,j - 1位置的值加1.而如果不能相连的话,就是i,j - 1或者i - 1,j位置值的最大值,因为有可能i不能和j相连但是能和j- 1相连,同理j也是一样。
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
# dp = [[0]*(len(B) + 1)] * (len(A) + 1)
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[len(A)][len(B)]