LeetCode 题解工作台
统计全 1 子矩形
给你一个 m x n 的二进制矩阵 mat ,请你返回有多少个 子矩形 的元素全部都是 1 。 示例 1: 输入: mat = [[1,0,1],[1,1,0],[1,1,0]] 输出: 13 解释: 有 6 个 1x1 的矩形。 有 2 个 1x2 的矩形。 有 3 个 2x1 的矩形。 有 1 …
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们可以枚举矩阵的右下角 $(i, j)$,然后向上枚举矩阵的第一行 ,那么每一行以 $(i, j)$ 为右下角的矩阵的宽度就是 $\min_{k \leq i} \textit{g}[k][j]$,其中 表示第 行以 $(k, j)$ 为右下角的矩阵的宽度。 因此,我们可以预处理得到二维数组 ,其中 表示第 行中,从第 列向左连续的 的个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个 m x n 的二进制矩阵 mat ,请你返回有多少个 子矩形 的元素全部都是 1 。
示例 1:

输入:mat = [[1,0,1],[1,1,0],[1,1,0]] 输出:13 解释: 有 6 个 1x1 的矩形。 有 2 个 1x2 的矩形。 有 3 个 2x1 的矩形。 有 1 个 2x2 的矩形。 有 1 个 3x1 的矩形。 矩形数目总共 = 6 + 2 + 3 + 1 + 1 = 13 。
示例 2:

输入:mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]] 输出:24 解释: 有 8 个 1x1 的子矩形。 有 5 个 1x2 的子矩形。 有 2 个 1x3 的子矩形。 有 4 个 2x1 的子矩形。 有 2 个 2x2 的子矩形。 有 2 个 3x1 的子矩形。 有 1 个 3x2 的子矩形。 矩形数目总共 = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24 。
提示:
1 <= m, n <= 150mat[i][j]仅包含0或1
解题思路
方法一:枚举 + 前缀和
我们可以枚举矩阵的右下角 ,然后向上枚举矩阵的第一行 ,那么每一行以 为右下角的矩阵的宽度就是 ,其中 表示第 行以 为右下角的矩阵的宽度。
因此,我们可以预处理得到二维数组 ,其中 表示第 行中,从第 列向左连续的 的个数。
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
g = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if mat[i][j]:
g[i][j] = 1 if j == 0 else 1 + g[i][j - 1]
ans = 0
for i in range(m):
for j in range(n):
col = inf
for k in range(i, -1, -1):
col = min(col, g[k][j])
ans += col
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate familiarity with dynamic programming and matrix manipulation techniques.
- question_mark
Look for a clear understanding of how to preprocess rows with the `nums` array to optimize the submatrix counting process.
- question_mark
Expect the candidate to discuss time and space complexities in the context of dynamic programming and matrix traversal.
常见陷阱
外企场景- error
Failing to optimize the solution by using the `nums` array can lead to inefficient brute-force counting.
- error
Overlooking the need for row-wise preprocessing of the matrix, which can hinder performance in larger test cases.
- error
Misunderstanding the role of dynamic programming and treating the problem as a straightforward iteration over all submatrices.
进阶变体
外企场景- arrow_right_alt
The problem can be generalized to non-binary matrices, where elements may have different values.
- arrow_right_alt
A variant could involve considering rectangles instead of squares in submatrices.
- arrow_right_alt
In a more challenging variant, you might be asked to find submatrices with a sum equal to a given target rather than all ones.