861. Score After Flipping Matrix**

861. Score After Flipping Matrix**

https://leetcode.com/problems/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 <= A.length <= 20
  • 1 <= A[0].length <= 20
  • A[i][j] is 0 or 1.

C++ 实现 1

只包含 0 和 1 的矩阵, 可以对其进行的操作是将某行或某列的值全部翻转, 0->1 而 1 变化为 0; 经过多次这样的翻转后, 每一行表示为一个二进制数, 求这些数的和中最大的是多少.

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,0,0],
 [1,0,1,0],
 [1,1,0,0]]
再变换为
[[1,1,1,1],
 [1,0,0,1],
 [1,1,1,1]].

思路: 贪心.

比如对于上面例子中的中间结果, 是考虑如果每行首个元素为 0, 那么就对这行进行翻转得到的.

[[1,1,0,0],
 [1,0,1,0],
 [1,1,0,0]]

为什么我知道下一次要改变最后两列呢? 这是因为第 2 列和第 3 列(即最后两列)中的 0 的个数比 1 的个数更多, 或者说, 我对某一列进行求和结果保存在 a 中, 行的个数为 m, 那么就需要比较 am - a 的大小, 如果 m - a 更大, 那么就可以对这一列进行翻转.

class Solution {
public:
    int matrixScore(vector<vector<int>>& A) {
        int m = A.size(), n = A[0].size();
        // 对每行首个元素为 0 的行进行翻转
        for (int i = 0; i < m; ++i) {
            if (A[i][0] == 0)
                for (int j = 0; j < n; ++j)
                    A[i][j] = 1 - A[i][j];
        }
        // 统计每列 1 的个数
        vector<int> tmp(n, 0);
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                tmp[j] += A[i][j];
		
        int res = 0;
        for (int j = 0; j < n; ++j) {
            if (tmp[j] < m - tmp[j]) // 如果当前列 0 的个数更多 (tmp[j] 目前表示 1 的个数)
                tmp[j] = m - tmp[j];
            res += tmp[j] * std::pow(2, n - 1 - j); // 每行第 j 个元素等于 1 的 10 进制为 2^{n - 1 -j}
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章