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]
相关推荐
WWZZ20251 小时前
ORB_SLAM2原理及代码解析:SetPose() 函数
人工智能·opencv·算法·计算机视觉·机器人·自动驾驶
小马学嵌入式~1 小时前
堆排序原理与实现详解
开发语言·数据结构·学习·算法
青岛少儿编程-王老师1 小时前
CCF编程能力等级认证GESP—C++6级—20250927
java·c++·算法
一人の梅雨1 小时前
1688 拍立淘接口深度开发:从图像识别到供应链匹配的技术实现
人工智能·算法·计算机视觉
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 64: 岛屿的最大面积、被围绕的区域
java·算法·leetcode·决策树·职场和发展·深度优先·推荐算法
Christo33 小时前
关于K-means和FCM的凸性问题讨论
人工智能·算法·机器学习·数据挖掘·kmeans
_不会dp不改名_3 小时前
leetcode_1382 将二叉搜索树变平衡树
算法·leetcode·职场和发展
greentea_20134 小时前
Codeforces Round 173 B. Digits(2043)
c++·算法
m0_743106464 小时前
LOBE-GS:分块&致密化效率提升
人工智能·算法·计算机视觉·3d·几何学
徐子童5 小时前
优选算法---字符串
java·算法·字符串·笔试·高精度相乘