题目:
We have a two dimensional matrix
A
where each value is0
or1
.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all0
s to1
s, and all1
s to0
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
.
解释:
方法:
1.对于开头为0的行,进行翻转
2.对于0的数目大于1的数目的列,进行翻转
翻转可以通过与1异或实现,也可以通过用1减去实现
python代码:
class Solution(object):
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A:
return 0
m=len(A)
n=len(A[0])
def fliprow(r):
for i in range(n):
A[r][i]^=1
def flipcol(c):
for i in range(m):
A[i][c]^=1
#第一步,对于开头为0的行,翻转
for i in range(m):
if A[i][0]==0:
fliprow(i)
#第二步,对于0的数目大于1的数目的列,进行翻转,不处理第0列,因为经过第一步以后,第0列全是1
#对于列进行遍历
for i in range(1,n):
sumofone=0
for j in range(m):
sumofone+=A[j][i]
if 2*sumofone<m :
flipcol(i)
#求和
_sum=0
for i in range(m):
_sum+=int(''.join(map(str,A[i])),2)
return _sum
c++代码:
#inlcude<cmath>
class Solution {
public:
int matrixScore(vector<vector<int>>& A) {
int m=A.size();
if(m==0)
return 0;
int n=A[0].size();
//对于第一列为0的行进行翻转
for(int i=0;i<m;i++)
if (A[i][0]==0)
flipr(i,A);
//对于0的个数大于1的个数的列,翻转
for(int i=0;i<n;i++)
{
int sumOne=0;
for (int j=0;j<m;j++)
if (A[j][i]==1)
sumOne++;
if (2*sumOne<m)
flipc(i,A);
}
//求和
int _sum=0;
for (int i=0;i<m;i++)
{
int base=pow(2,n-1);
for (int j=0;j<n;j++)
{
_sum+=base*A[i][j];
base/=2;
}
}
return _sum;
}
void flipr(int r,vector<vector<int>>& A)
{
for(int i=0;i<A[0].size();i++)
A[r][i]=1-A[r][i];
}
void flipc(int c,vector<vector<int>>& A)
{
for (int i=0;i<A.size();i++)
A[i][c]=1-A[i][c];
}
};
总结: