每⽇⼀道笔试题,同学们可以进⾏⾃我测试⼀下,下午公布参考答案~
在两条独⽴的⽔平线上按给定的顺序写下 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);
}
}