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]
相关推荐
TracyCoder1239 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u01092727110 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_9418372610 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义11 小时前
java基础十二
java·数据结构·算法
四维碎片11 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs11 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E12 小时前
【优先级队列】主持人调度(二)
算法
weixin_4454766812 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王13 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区13 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展