第一次手搓一个回溯法,超时后采用枝剪勉强通过
class Solution { int max=0; int numSelect; public int maximumRows(int[][] matrix, int numSelect) { Set<String>stateSet=new HashSet<>(); dfs(matrix,new boolean[matrix[0].length],0,numSelect,stateSet); return max; } public void dfs(int[][]matrix,boolean[]selected,int step,int numSelect,Set<String>stateSet){ String currentState = Arrays.toString(selected); if (stateSet.contains(currentState)) return; else stateSet.add(currentState); if(step==numSelect){ int cnt=0; for(int i=0;i<matrix.length;i++){ boolean flag=true; for(int j=0;j<matrix[0].length;j++){ if(matrix[i][j]!=0&&!selected[j]){ flag=false; break; } } if(flag) cnt++; } max=Math.max(max,cnt); return; } for(int i=0;i<selected.length;i++){ if(!selected[i]){ selected[i]=true; dfs(matrix,selected,step+1,numSelect,stateSet); selected[i]=false; } } } }
标签:numSelect,matrix,int,stateSet,leetcode2397,回溯,被列,currentState From: https://www.cnblogs.com/kun1790051360/p/18066635