LC.P2397[被列覆盖的最多行数]

方法一:二进制枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int maximumRows(int[][] matrix, int numSelect) {
int m = matrix.length, n = matrix[0].length;
int[] rows = new int[m];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (matrix[i][j] == 1) {
rows[i] |= 1 << j;
}
}
}
int ans = 0;
for (int mask = 1; mask < 1 << n; ++mask) {
if (Integer.bitCount(mask) != numSelect) continue;
int t = 0;
for (int x : rows) {
if ((x & mask) == x) {
++t;
}
}
ans = Math.max(ans, t);
}
return ans;
}
}
  • 时间复杂度:$O(2^n \times m)$
  • 空间复杂度:$O(m)$