1 题目
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]
is0
or1
.
2 尝试解
2.1 分析
给定一个由0和1组成的矩阵,可以对某一行或某一列进行异或操作。如果每一行代表一个二进制的整数,求任意操作后,可以得到的所有数之和最大值。
行操作会改变最高位的数字,所以只能用于首位为0的行。先通过行操作,将第一列数字全变为1,那么只要不改变第一列,所有的行操作都只会使和减小,那么只有列操作可行。从第2列开始,如果该列中0比1多,则对该列使用列操作。最后求和即可。
2.2 代码
class Solution {
public:
int matrixScore(vector<vector<int>>& A) {
int result = 0;
for(int i = 0; i < A.size(); i++){
if(!A[i][0]){
for(int j = 0; j < A[i].size();j++){
A[i][j] = 1 - A[i][j];
}
}
}
result = A.size();
for(int i = 1; i < A[0].size(); i++){
int count = 0;
for(int j = 0; j < A.size(); j++){
if(A[j][i])
count++;
}
result = 2*result + (2*count<A.size()?A.size()-count:count);
}
return result;
}
};
3 标准解
class Solution {
public:
int matrixScore(vector<vector<int>> A) {
int M = A.size(), N = A[0].size(), res = (1 << (N - 1)) * M;
for (int j = 1; j < N; j++) {
int cur = 0;
for (int i = 0; i < M; i++) cur += A[i][j] == A[i][0];
res += max(cur, M - cur) * (1 << (N - j - 1));
}
return res;
}
};