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 0s to 1s, and all 1s to 0s.
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.
对于一个由0和1构成的矩阵,对于每一行和每一列都可以进行翻转——即0变成1,1变成0;求翻转结果的最大值。
2,题目思路
对于这一题,首先,对于这个矩阵每一行的第一个数字,当它为1时,一定是最大的,即:
1000 > 0111。
其次,再遍历这个矩阵除了第一列之外的所有列。
因为我们一定要将A[i][0]置位1,因此对于每一列中的A[i][j],如果它的值等于A[i][0],则说明它可以置位1,也就说说可以置位1的个数多了一个。
但是,这样的置换并不能保证所得的结果一定是最大的,因此要看如果这样翻转后,得到的1是不是最多的,如果是最多的,则计算这样的1所构成的二进制数的最大值。否则,就按照原先的1的形式计算(翻转两次即可)。
3,程序源码
class Solution {
public:
int matrixScore(vector<vector<int>>& A) { //对行和列进行flip,其中A是M*N的矩阵(flip:1->0, 0->1)
int M = A.size(), N = A[0].size();
int res = (1<<(N-1)) * M; //每一行的一个元素都应该被翻转为1,这样的到的数字才是最大的
for(int j = 1;j < N;j++)
{
int tmp = 0;//每一列中,在flip后可以得到的1的个数
for(int i = 0;i < M;i++)
{
if(A[i][j] == A[i][0])
tmp++;
}
int max_1 = max(M-tmp, tmp);//即翻转后的1的个数多,还是再翻转一次变为原样的1的个数多。
cout<<max_1<<endl;
res += max_1 * (1<<(N-1-j));
}
return res;
}
};