代码随想录——不相交的线(Leetcode 1035)

题目链接
在这里插入图片描述

动态规划

思路:本题等价于求最长公共子序列

class Solution {
    
    
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
    
    
        int[][] dp = new int[nums1.length + 1][nums2.length + 1];
        int res = 0;
        for(int i = 1; i < nums1.length + 1; i++){
    
    
            for(int j = 1; j < nums2.length + 1; j++){
    
    
                if(nums1[i - 1] == nums2[j - 1]){
    
    
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else{
    
    
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
                }
                res = Math.max(res, dp[i][j]);
            }
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_46574748/article/details/141012646