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

861. Score After Flipping Matrix

str nsis pan core auto input number urn value

題目描述:

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.

解題思路:

對於一個矩陣有兩種變換,行和列上面的取反。

對於行變換,若首位數字不為1時,將進行行變化,此時整體數值變大。

對於列變換,從第二列開始,統計每列的1和0的個數,若0的個數多余1的個數時,進行列變換,此時整體數值變大。

代碼:

 1 class Solution {
 2 public:
 3     int matrixScore(vector<vector<int>>& A) {
 4         for (auto & vec : A) {
 5             if (!vec[0])
 6                 togging(vec);
 7         }
 8         for (int i = 1; i < A[0
].size() ; ++i){ 9 int zero = 0; 10 int one = 0; 11 for (int j = 0; j < A.size(); ++j){ 12 if (A[j][i]) 13 one++; 14 else 15 zero++; 16 } 17 if (zero>one){ 18 for (int j = 0; j < A.size(); j++){ 19 A[j][i] = !A[j][i]; 20 } 21 } 22 } 23 int num = 0; 24 for (auto vec :A) { 25 for (int i = 0; i < vec.size(); i++){ 26 num += vec[i] *pow(2, (vec.size()-1-i)); 27 } 28 } 29 return num; 30 } 31 void togging(vector<int>& vec){ 32 for(int i = 0; i <vec.size(); i++){ 33 vec[i] = !vec[i]; 34 } 35 } 36 };

861. Score After Flipping Matrix