LeetCode 题解工作台

翻转矩阵后的得分

给你一个大小为 m x n 的二元矩阵 grid ,矩阵中每个元素的值为 0 或 1 。 一次 移动 是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1 ,将所有 1 都更改为 0 。 在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的 得分 就是这些数字的总…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们注意到,对于任意一个翻转方案,翻转的次序不影响最后的结果。因此我们可以先考虑所有的行翻转,再考虑所有的列翻转。 每一行的数字要尽可能大,因此,我们遍历每一行,若行首元素为 ,则将该行进行翻转。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个大小为 m x n 的二元矩阵 grid ,矩阵中每个元素的值为 01

一次 移动 是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0

在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的 得分 就是这些数字的总和。

在执行任意次 移动 后(含 0 次),返回可能的最高分数。

 

示例 1:

输入:grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
输出:39
解释:0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

示例 2:

输入:grid = [[0]]
输出:1

 

提示:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 20
  • grid[i][j]01
lightbulb

解题思路

方法一:贪心

我们注意到,对于任意一个翻转方案,翻转的次序不影响最后的结果。因此我们可以先考虑所有的行翻转,再考虑所有的列翻转。

每一行的数字要尽可能大,因此,我们遍历每一行,若行首元素为 00,则将该行进行翻转。

接下来,对于每一列 jj,我们统计该列中 0011 的数量,令 cntcnt 为其中的最大值,则该列的贡献为 cnt×2nj1cnt \times 2^{n - j - 1}。对所有列的贡献进行累加,即可得到答案。

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(1)O(1)。其中 mm, nn 分别为矩阵的行数和列数。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def matrixScore(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        for i in range(m):
            if grid[i][0] == 0:
                for j in range(n):
                    grid[i][j] ^= 1
        ans = 0
        for j in range(n):
            cnt = sum(grid[i][j] for i in range(m))
            ans += max(cnt, m - cnt) * (1 << (n - j - 1))
        return ans
speed

复杂度分析

指标
时间O(m \cdot n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an approach that efficiently handles the greedy choice of flipping rows and columns.

  • question_mark

    Ensure the candidate can correctly apply invariant validation to the matrix after row flips.

  • question_mark

    The candidate should demonstrate the ability to compute the final score efficiently.

warning

常见陷阱

外企场景
  • error

    Failing to flip rows initially to ensure the most significant bit is 1.

  • error

    Not correctly validating column flips based on the number of 1's and 0's.

  • error

    Overcomplicating the solution by not sticking to the greedy choice plus invariant validation pattern.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider the scenario where m or n is at the upper limit of 20, testing the scalability of the approach.

  • arrow_right_alt

    Modify the problem to allow flipping only rows or only columns, testing how the solution adapts to different constraints.

  • arrow_right_alt

    Introduce additional constraints on which rows and columns can be flipped based on certain conditions, adding complexity to the problem.

help

常见问题

外企场景

翻转矩阵后的得分题解:贪心·invariant | LeetCode #861 中等