2018/12/2
861. 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 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.
测试样例
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.
问题分析
本题难度为Medium!属于贪心问题,已给出的函数定义为
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
本题的目的是矩阵各行表示的二进制数和最大,则要求最高位尽可能为1,因此本题的思路为首先改变每一行使得每一行的最高位为1,然后遍历所有非最高位的列,使得每一列的1的个数尽可能的多,这样最终结果最大。
代码实现
python3
# coding: utf-8
# coding: utf-8
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
temp_A = A.copy()
row = len(temp_A)
col = len(temp_A[0])
def changeRow(A, n): # 改变A数组的第n行(0,1,...)
for i in range(len(A[n])):
A[n][i] = 1 if A[n][i] == 0 else 0
def changeCol(A, n): # 改变A数组的第n列(0,1,...)
for i in range(len(A)):
A[i][n] = 1 if A[i][n] == 0 else 0
# 所有最高位变为1
for i in range(row):
if temp_A[i][0] != 1:
changeRow(temp_A, i)
# 非最高位使每一列的1尽可能多
for i in range(1,col):
count_of_1 = 0
for j in range(row):
count_of_1 += temp_A[j][i]
if count_of_1 < row/2:
changeCol(temp_A, i)
# 计算和
res = 0
for i in range(col):
for j in range(row):
res += temp_A[j][i] * (2**(col-1-i))
return res