leecode1035. 不相交的线

在两条独立的水平线上按给定的顺序写下 nums1 和 nums2 中的整数。

现在,可以绘制一些连接两个数字 nums1[i] 和 nums2[j] 的直线,这些直线需要同时满足满足:

 nums1[i] == nums2[j]
且绘制的直线不与任何其他连线(非水平线)相交。
请注意,连线即使在端点也不能相交:每个数字只能属于一条连线。

以这种方法绘制线条,并返回可以绘制的最大连线数。

示例 1:


输入:nums1 = [1,4,2], nums2 = [1,2,4]
输出:2
解释:可以画出两条不交叉的线,如上图所示。 
但无法画出第三条不相交的直线,因为从 nums1[1]=4 到 nums2[2]=4 的直线将与从 nums1[2]=2 到 nums2[1]=2 的直线相交。
示例 2:

输入:nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]
输出:3
示例 3:

输入:nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]
输出:2
 

提示:

1 <= nums1.length, nums2.length <= 500
1 <= nums1[i], nums2[j] <= 2000
 

思路:使用记忆化搜索

class Solution {
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int[][] arr = new int[nums1.length][nums2.length];
        for (int i = 0; i < nums1.length; i++) {
            for (int j = 0; j < nums2.length; j++) {
                arr[i][j] = -1;
            }
        }
        return dfs(nums1, 0, nums2, 0,arr);
    }

    public int dfs(int[] nums1, int index1, int[] nums2, int index2, int[][] arr) {
        if (index1 == nums1.length || index2 == nums2.length) {
            return 0;
        }
        if (arr[index1][index2] == -1) {
            //两个数组当前如果相等
            if (nums1[index1] == nums2[index2]) {
                //1.选择连线,都往前移动1
                //2.数组1往前移动1
                //3.数组2往前移动1
                //4.数组1,2都往前移动1
                int r = Math.max(dfs(nums1, index1+1, nums2, index2, arr), dfs(nums1, index1, nums2, index2+1, arr));
                int r1 = Math.max(r, dfs(nums1, index1+1, nums2, index2+1, arr));
                arr[index1][index2] = Math.max(Math.max(r, r1),1 + dfs(nums1, index1+1, nums2, index2+1, arr));

            } else {
                //2.数组1往前移动1
                //3.数组2往前移动1
                //4.数组1,2都往前移动1
                int r = Math.max(dfs(nums1, index1+1, nums2, index2,arr), dfs(nums1, index1, nums2, index2+1,arr));
                int r1 = Math.max(r, dfs(nums1, index1+1, nums2, index2+1,arr));
                arr[index1][index2] = Math.max(r, r1);
            }
        }
        return arr[index1][index2];


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值