Approach
Depth-first search
For Maximum Rows Covered by Columns, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 39 lines of Java from the credited upstream file 2397.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maximumRows(int[][] matrix, int numSelect) {3 dfs(matrix, 0, numSelect, 0);4 return ans;5 }6 7 private int ans = 0;8 9 private void dfs(int[][] matrix, int colIndex, int leftColsCount, int mask) {10 if (leftColsCount == 0) {11 ans = Math.max(ans, getAllZerosRowCount(matrix, mask));12 return;13 }14 if (colIndex == matrix[0].length)15 return;16 17 18 dfs(matrix, colIndex + 1, leftColsCount - 1, mask | 1 << colIndex);19 20 dfs(matrix, colIndex + 1, leftColsCount, mask);21 }22 23 int getAllZerosRowCount(int[][] matrix, int mask) {24 int count = 0;25 for (int[] row : matrix) {26 boolean isAllZeros = true;27 for (int i = 0; i < row.length; ++i) {28 if (row[i] == 1 && (mask >> i & 1) == 0) {29 isAllZeros = false;30 break;31 }32 }33 if (isAllZeros)34 ++count;35 }36 return count;37 }38}39