题目地址
LeetCode#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:
1 | Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]] |
Note:
1 <= A.length <= 201 <= A[0].length <= 20A[i][j]is0or1.
解题思路
贪心算法,我们知道二进制串中越高位的占的比重越大,所以我们可以直接从高到底来判断是否进行 toggling 操作。
首先为行,行中每个数字的权重不一样,从高往低,所以在行中我们只需要对第一位进行判断(即数组第一个数字),当他为0的时候我们要将他变为1 就需要 toggling ,这样可以使这一行数字的二进制串最大。
列中每一列的权重一样,所以我们需要判断这一列中1的个数和0的个数,当0的个数大于1的个数时我们进行 toggling 操作。
解题代码
1 | class Solution { |