861. Score After Flipping Matrix

Posted zzz-y

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.

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

一个由0和1构成的矩阵,每次可以选择任意一行或列,行或列的数字0变成1,1变成0.

每一行代表一个二进制数,求能够成的这些二进制数和的最大值

 

由二进制转十进制原理,1的位置越靠前越好,所以第一步,把每一行的第一个数变成1.

第二步,对除了第一列外的每一列的1的个数做统计,如果翻转后能增加1的个数,就翻转该列。

 

 1 class Solution {
 2 public:
 3     int matrixScore(vector<vector<int>>& A) {
 4         int row = A.size();
 5         int col = A[0].size();
 6         vector<int> cnt(col, 0);
 7         for (int i = 0; i < row; ++i) {
 8             if (A[i][0] == 0) {
 9                 for (int j = 0; j < col; ++j) {
10                     A[i][j] = 1 - A[i][j];
11                     if (A[i][j] == 1)   ++cnt[j];
12                 }
13             }
14             else {
15                 for (int j = 0; j < col; ++j) {
16                     if (A[i][j] == 1)  ++cnt[j];
17                 }
18             }
19         }
20         for (int j = 1; j < col; ++j) {
21             if (cnt[j] * 2 < row) {
22                 for (int i = 0; i < row; ++i)
23                     A[i][j] = 1 - A[i][j];
24             }
25         }
26         int sum = 0;
27         int v = 0;;
28         int res = 0;
29         for (int i = 0; i < row; ++i) {
30             sum = 0;
31             v = 1;
32             for (int j = col - 1; j >= 0; --j) {
33                 sum += A[i][j] * v;
34                 v = v * 2;
35             }
36             res += sum;    
37         }
38         return res;   
39     }
40 };

 

以上是关于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