被列覆盖的最多行数
思路
1、使用回溯算法,不断的尝试覆盖numselect行数
2、找到最大覆盖行数
代码
import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Solution solution = new Solution(); int res = solution.maximumRows(new int[][]{ {0,0,0,1}, {0,1,0,1}, {0,0,0,1}, {0,1,0,1}, }, 1); System.out.println(res); } } class Solution { int max; public int maximumRows(int[][] matrix, int numSelect) { if (matrix[0].length <= numSelect){ return matrix.length; } int[] row = new int[matrix[0].length]; for (int i = 0; i < row.length; i++) { row[i] = i; } calMaxRows(row, 0, numSelect, matrix); return max; } private void calMaxRows(int[] row, int index, int numSelect, int[][] matrix) { if (index == numSelect){ max = Math.max(max, calRow(row, numSelect, matrix)); return; } for (int i = index; i < row.length; i++) { swap(index, i, row); calMaxRows(row, index + 1, numSelect, matrix); swap(i, index, row); } } private void swap(int i, int j, int[] row) { int temp = row[i]; row[i] = row[j]; row[j] = temp; } private int calRow(int[] rows, int numSelect, int[][] matrix) { HashSet<Integer> selectRows = new HashSet<>(); for (int i = 0; i < numSelect; i++) { selectRows.add(rows[i]); } int res = 0; for (int[] ints : matrix) { boolean flag = true; for (int col = 0; col < matrix[0].length; col++) { if (selectRows.contains(col)) { continue; } if (ints[col] != 0) { flag = false; break; } } if (flag) { res++; } } return res; } }
Linux等环境软件安装