贪心,LeetCode

question

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

题解

观察可得——要返回值尽可能大,那么最左边一列的元素必须1

经过行反转后得到最左边一列的元素全为1,接下来只能进行列反转

每一列中,如果值为1的个数小于值为0的个数就进行列反转(取Math.max(oneSum,zeroSum),其中oneNumberSum+zeroNumberSum = m,此时我们用进行oneNumberSum进行标记)

但是在计算个数要考虑第一步的行反转,此时考虑第三行

for(int j = 1; j < A[0].length;j++)
{
    if (A[3][0] == 0)
        A[3][j] = 1 - A[3][j]; //1变0,0变1
}

代码

class Solution {
    public int matrixScore(int[][] A) {
        int m = A.length;
        int n = A[0].length;
        int sum = m * (1<<n-1);
        for (int i = 1; i < n; i++) {
            int oneSum = 0; //算出这列值为1的元素个数
            for (int j = 0; j < m; j++) {
                if (A[j][0]==1) //第j行最左边的元素为1,此行未发生反转
                    oneSum+=A[j][i];
                else    //第j行最左边的元素为0,此行发生反转(此行元素0变1,1变0)
                    oneSum += 1-A[j][i];
            }
            int k = Math.max(oneSum,m-oneSum); //取值为1元素和个数和值为0元素的个数中多的那个
            sum += k*(1<<(n-1-i)); 
        }
        return sum;
    }
}
Pay by WeChat

Pay by WeChat

Comment

This is just a placeholder img.