5月挑战Day25-Uncrossed Lines(Medium)

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)]

这个有两个注意的地方:注释的地方是我原先设置初始数组的方式,但是这种方式似乎会引发一种浅拷贝的问题,在数组更新的过程中,改一个值就会改动这个值所在的列所有的值,所以用了第二种方式重新建立了一个数组。关于这个问题的解释请看python-如何创建二维数组。还有一点就是我们在建数组时多一维建立,这个我们可以避免判断数组越界的情况。时间复杂度为O(mn),m,n为数组A,B的长度。空间复杂度为O((m+1) * (n + 1))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值