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]
相关推荐
小白菜又菜4 小时前
Leetcode 3370. Smallest Number With All Set Bits
算法·leetcode·职场和发展
星谷罗殇5 小时前
(七)TRPO 算法 & PPO 算法
算法·机器学习
国服第二切图仔6 小时前
Rust开发之使用Trait对象实现多态
开发语言·算法·rust
电鱼智能的电小鱼7 小时前
基于电鱼 ARM 工控机的井下AI故障诊断方案——让煤矿远程监控更智能、更精准
网络·arm开发·人工智能·算法·边缘计算
s砚山s7 小时前
代码随想录刷题——二叉树篇(一)
c++·算法·leetcode
贝塔实验室10 小时前
LDPC 码的构造方法
算法·fpga开发·硬件工程·动态规划·信息与通信·信号处理·基带工程
Greedy Alg10 小时前
LeetCode 287. 寻找重复数
算法
2501_9387912210 小时前
逻辑回归与KNN在低维与高维数据上的分类性能差异研究
算法·分类·逻辑回归
南方的狮子先生10 小时前
【深度学习】60 分钟 PyTorch 极速入门:从 Tensor 到 CIFAR-10 分类
人工智能·pytorch·python·深度学习·算法·分类·1024程序员节
报错小能手10 小时前
C++笔记(面向对象)类模板
算法