861. Score After Flipping Matrix

Posted gsz-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

解题思路:

对于一个矩阵有两种变换,行和列上面的取反。

对于行变换,若首位数字不为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的主要内容,如果未能解决你的问题,请参考以下文章

861. Score After Flipping Matrix

算法leetcode861. 翻转矩阵后的得分(多语言实现)

算法leetcode861. 翻转矩阵后的得分(多语言实现)

[LeetCode] Score After Flipping Matrix 翻转数组后的分数

leetcode1422. Maximum Score After Splitting a String

leetcode1422. Maximum Score After Splitting a String