Skip to content

Commit 5241b54

Browse files
committed
add: 被列覆盖的最多行数
1 parent 14569cc commit 5241b54

5 files changed

+69
-1
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -814,3 +814,7 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文
814814
- [一周中的第几天](src/math/day_of_the_week.cpp) [数学]
815815

816816
- LeetCode 1185. 一周中的第几天 <https://leetcode.cn/problems/day-of-the-week>
817+
818+
- [被列覆盖的最多行数](src/math/maximum_rows_covered_by_columns.cpp) [位运算, 数组, 回溯, 枚举, 矩阵]
819+
820+
- LeetCode 2397. 被列覆盖的最多行数 <https://leetcode.cn/problems/maximum-rows-covered-by-columns>
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// 被列覆盖的最多行数
2+
// https://leetcode.cn/problems/maximum-rows-covered-by-columns
3+
// INLINE ../../images/math/maximum_rows_covered_by_columns.jpeg
4+
5+
#include <headers.hpp>
6+
7+
class Solution {
8+
public:
9+
int maximumRows(vector<vector<int>> &matrix, int numSelect) {
10+
int m = matrix.size(), n = matrix[0].size();
11+
vector<int> mask(m, 0);
12+
for (int i = 0; i < m; i++) {
13+
for (int j = 0; j < n; j++) {
14+
mask[i] += matrix[i][j] << (n - j - 1);
15+
}
16+
}
17+
int res = 0;
18+
int cur = 0;
19+
int limit = (1 << n);
20+
while ((++cur) < limit) {
21+
if (__builtin_popcount(cur) != numSelect) {
22+
continue;
23+
}
24+
int t = 0;
25+
for (int j = 0; j < m; j++) {
26+
if ((mask[j] & cur) == mask[j]) {
27+
++t;
28+
}
29+
}
30+
res = max(res, t);
31+
}
32+
return res;
33+
}
34+
};

test/lib/lib_test.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 执行编译时间:2024-01-03 10:37:56
1+
// 执行编译时间:2024-01-04 09:37:38
22
#include <gtest/gtest.h>
33
#include <lib.hpp>
44

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <math/maximum_rows_covered_by_columns.cpp>
2+
3+
TEST(被列覆盖的最多行数, maximumRows) {
4+
Solution solution;
5+
// 示例 1:
6+
// 输入:matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2
7+
// 输出:3
8+
// 解释:
9+
// 图示中显示了一种覆盖 3 行的可行办法。
10+
// 选择 s = {0, 2} 。
11+
// - 第 0 行被覆盖,因为其中没有出现 1 。
12+
// - 第 1 行被覆盖,因为值为 1 的两列(即 0 和 2)均存在于 s 中。
13+
// - 第 2 行未被覆盖,因为 matrix[2][1] == 1 但是 1 未存在于 s 中。
14+
// - 第 3 行被覆盖,因为 matrix[2][2] == 1 且 2 存在于 s 中。
15+
// 因此,可以覆盖 3 行。
16+
// 另外 s = {1, 2} 也可以覆盖 3 行,但可以证明无法覆盖更多行。
17+
vector<vector<int>> matrix = {{0, 0, 0}, {1, 0, 1}, {0, 1, 1}, {0, 0, 1}};
18+
int numSelect = 2;
19+
EXPECT_EQ(solution.maximumRows(matrix, numSelect), 3);
20+
21+
// 示例 2:
22+
// 输入:matrix = [[1],[0]], numSelect = 1
23+
// 输出:2
24+
// 解释:
25+
// 选择唯一的一列,两行都被覆盖了,因为整个矩阵都被覆盖了。
26+
// 所以我们返回 2 。
27+
matrix = {{1}, {0}};
28+
numSelect = 1;
29+
EXPECT_EQ(solution.maximumRows(matrix, numSelect), 2);
30+
}

0 commit comments

Comments
 (0)