华为笔试3.23第三题代码讨论
辣鸡输出,弄了两个小时不确定能不能通过所有case
/* 4 6 4 Java C++ Python Python C++ Java Python Java Python C++ Python C++ Java true 1 0 1 0 1 1 0 1 0 1 0 0 1 0 1 0 1 1 0 1 0 1 0 0 */ // We have imported the necessary tool classes. // If you need to import additional packages or classes, please import here. import java.util.Scanner; public class Solution { static boolean flag=false; static int[][] num; public static int[][] match(String[] str1,String[] str2,int k){ int n=str1.length; int m=str2.length; int[][] nums=new int[n][m]; num=new int[n][m]; dfs(nums,0,0,str1,str2,k,0); return num; } public static void dfs(int[][] nums,int index,int start,String[] str1,String[] str2,int k,int sum){ int n=nums.length; int m=nums[0].length; if(index==m){ if(check(nums,k)){ flag=true; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ num[i][j]=nums[i][j]; } } } return ; } for(int i=start;i<n;i++){ String cur=str2[index]; if(str1[i].indexOf(cur)!=-1 && nums[i][index]==0){ if(sum==0){ nums[i][index]=1; sum++; dfs(nums,index,i+1,str1,str2,k,sum); nums[i][index]=0; sum--; } if(sum==1){ nums[i][index]=1; sum++; dfs(nums,index+1,0,str1,str2,k,0); nums[i][index]=0; sum--; } } } } public static boolean check(int[][] nums,int k){ int n=nums.length; int m=nums[0].length; for(int i=0;i<n;i++){ int sum=0; for(int j=0;j<m;j++){ if(nums[i][j]==1){ sum++; } if(sum>k) return false; } } for(int i=0;i<m;i++){ int sum=0; for(int j=0;j<n;j++){ if(nums[j][i]==1){ sum++; } } if(sum!=2) return false; } return true; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int m=in.nextInt(); int n=in.nextInt(); int k=in.nextInt(); String[] str1=new String[m]; String s=in.nextLine(); for(int i=0;i<m;i++){ str1[i]=in.nextLine().trim(); } String[] str2=new String[n]; for(int i=0;i<n;i++){ str2[i]=in.nextLine().trim(); } match(str1,str2,k); if(!flag){ System.out.println(false); }else{ System.out.println(true); for(int i=0;i<m;i++){ StringBuilder sb=new StringBuilder(); for(int j=0;j<n;j++){ sb.append(num[i][j]+" "); } System.out.println(sb.toString()); } } } }