1. 程式人生 > >LC 861. Score After Flipping Matrix

LC 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. 1 <= A.length <= 20
  2. 1 <= A[0].length <= 20
  3. A[i][j] is 0
     or 1.

 

Runtime: 4 ms, faster than 58.17% of C++ online submissions for Score After Flipping Matrix.

注意一下,首列如果某行從0換成1那麼在之後計算這一行時要反向。

class Solution {
public:
  int matrixScore(vector<vector<int>>& A) {
    int r = A.size();
    
int c = A[0].size(); vector<int> rsign(r,0); int base = 1 << (A[0].size()-1), ret = 0; for(int j=0; j<c; j++){ int cntzero = 0, cntone = 0; for(int i=0; i<r; i++){ if(j == 0){ if(A[i][j] != 0) rsign[i]++; }else{ if((A[i][j] == 0 && rsign[i] == 0) || (A[i][j] == 1 && rsign[i] == 1)) cntzero++; else cntone++; } } if(j == 0){ ret += base * r; } else if(cntzero > cntone) { ret += base * cntzero; }else ret += base * cntone; base >>= 1; } return ret; } };