861. Score After Flipping Matrix**
https://leetcode.com/problems/score-after-flipping-matrix/
題目描述
We have a two dimensional matrix A
where each value is 0
or 1
.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0
s to 1
s, and all 1
s to 0
s.
After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.
Example 1:
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Note:
1 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j]
is 0 or 1.
C++ 實現 1
只包含 0 和 1 的矩陣, 可以對其進行的操作是將某行或某列的值全部翻轉, 0->1
而 1 變化爲 0; 經過多次這樣的翻轉後, 每一行表示爲一個二進制數, 求這些數的和中最大的是多少.
Input:
[[0,0,1,1],
[1,0,1,0],
[1,1,0,0]]
Output: 39
Explanation:
Toggled to
[[1,1,1,1],
[1,0,0,1],
[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
因爲先變化爲
[[1,1,0,0],
[1,0,1,0],
[1,1,0,0]]
再變換爲
[[1,1,1,1],
[1,0,0,1],
[1,1,1,1]].
思路: 貪心.
比如對於上面例子中的中間結果, 是考慮如果每行首個元素爲 0
, 那麼就對這行進行翻轉得到的.
[[1,1,0,0],
[1,0,1,0],
[1,1,0,0]]
爲什麼我知道下一次要改變最後兩列呢? 這是因爲第 2 列和第 3 列(即最後兩列)中的 0 的個數比 1 的個數更多, 或者說, 我對某一列進行求和結果保存在 a
中, 行的個數爲 m
, 那麼就需要比較 a
與 m - a
的大小, 如果 m - a
更大, 那麼就可以對這一列進行翻轉.
class Solution {
public:
int matrixScore(vector<vector<int>>& A) {
int m = A.size(), n = A[0].size();
// 對每行首個元素爲 0 的行進行翻轉
for (int i = 0; i < m; ++i) {
if (A[i][0] == 0)
for (int j = 0; j < n; ++j)
A[i][j] = 1 - A[i][j];
}
// 統計每列 1 的個數
vector<int> tmp(n, 0);
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
tmp[j] += A[i][j];
int res = 0;
for (int j = 0; j < n; ++j) {
if (tmp[j] < m - tmp[j]) // 如果當前列 0 的個數更多 (tmp[j] 目前表示 1 的個數)
tmp[j] = m - tmp[j];
res += tmp[j] * std::pow(2, n - 1 - j); // 每行第 j 個元素等於 1 的 10 進製爲 2^{n - 1 -j}
}
return res;
}
};