算法训练——数组匹配最多连线数

每⽇⼀道笔试题,同学们可以进⾏⾃我测试⼀下,下午公布参考答案~

        在两条独⽴的⽔平线上按给定的顺序写下 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

解题:dfs神搜

public class Day3 {

    public static void main(String[] args) {
//        int solution = new Day3().solution(new int[]{1, 4, 2}, new int[]{1, 2, 4}, 0, 0,0);
//        int solution = new Day3().solution(new int[]{1,3,7,1,7,5}, new int[]{1,9,2,5,1}, 0, 0,0);
//        int solution = new Day3().solution(new int[]{1,3,7,5}, new int[]{3,7,5,1}, 0, 0,0);
//        System.out.println(max);
    }

    public int solution(int[] nums1, int[] nums2){
        max = 0;
        solution(nums1,nums2,0,0,0);
        return max;
    }

    static int max = 0;

    public void solution(int[] nums1, int[] nums2, int start1, int start2 ,int temp) {
        if (start2 >= nums2.length || start1 >= nums1.length) {
            max = Math.max(temp,max);
        }

        for (int i = start1; i < nums1.length; i++) {
            for (int j = start2; j < nums2.length; j++) {
                if (nums2[j] == nums1[i]) {
                    solution(nums1, nums2, i + 1, j + 1 ,temp + 1);
                }
            }
        }
        max = Math.max(temp,max);
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aristocrat l

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值