Leetcode 1035. Uncrossed Lines

Problem

You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.

We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[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.

Algorithm

Dynamic Programming (DP): same as Longest Common Subsequence (LCS).

  • If s1[i] != s2[j]:
    F ( i , j ) = max ⁡ ( F ( i − 1 , j ) , F ( i , j − 1 ) ) F(i, j) = \max\left( F(i-1, j), F(i, j-1) \right) F(i,j)=max(F(i−1,j),F(i,j−1))

  • If s1[i] == s2[j]:
    F ( i , j ) = F ( i − 1 , j − 1 ) + 1 F(i, j) = F(i-1, j-1) + 1 F(i,j)=F(i−1,j−1)+1

Code

python3 复制代码
class Solution:
    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
        l1, l2 = len(nums1) + 1, len(nums2) + 1
        dp = [[0] * l2 for _ in range(l1)] 

        for i in range(1, l1):
            for j in range(1, l2):
                if nums1[i-1] == nums2[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[l1-1][l2-1]
相关推荐
I_LPL3 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱3 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073214 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
2401_831824965 小时前
代码性能剖析工具
开发语言·c++·算法
Sunshine for you6 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018726 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563246 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920746 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703316 小时前
上机练习第51天
数据结构·c++·算法
ArturiaZ6 小时前
【day60】
算法·深度优先·图论