LeetCode 题解工作台
最大正方形
在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。 示例 1: 输入: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 $dp[i + 1][j + 1]$ 表示以下标 $(i, j)$ 作为正方形右下角的最大正方形边长。答案为所有 $dp[i + 1][j + 1]$ 中的最大值。 状态转移方程为:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] 输出:4
示例 2:
输入:matrix = [["0","1"],["1","0"]] 输出:1
示例 3:
输入:matrix = [["0"]] 输出:0
提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 300matrix[i][j]为'0'或'1'
解题思路
方法一:动态规划
我们定义 表示以下标 作为正方形右下角的最大正方形边长。答案为所有 中的最大值。
状态转移方程为:
时间复杂度 ,空间复杂度 。其中 和 分别是矩阵的行数和列数。
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
mx = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i + 1][j], dp[i][j]) + 1
mx = max(mx, dp[i + 1][j + 1])
return mx * mx
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m * n) where m and n are the dimensions of the matrix, as each cell is processed once. Space complexity can be optimized to O(n) by keeping only the current and previous rows of the DP matrix, reducing the overall space usage from O(m * n). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Assess the candidate's ability to optimize space in dynamic programming solutions.
- question_mark
Evaluate how well the candidate explains and uses state transitions in dynamic programming.
- question_mark
Check if the candidate can identify the trade-offs between time and space complexities.
常见陷阱
外企场景- error
Forgetting to initialize the first row and first column of the DP matrix correctly.
- error
Using a brute force approach to check every potential square without leveraging dynamic programming.
- error
Not optimizing space by reducing the DP matrix to only necessary rows.
进阶变体
外企场景- arrow_right_alt
Modify the problem to find the largest square of 1's within a submatrix of the matrix.
- arrow_right_alt
Consider a version where the matrix size can vary during runtime or input.
- arrow_right_alt
Challenge the candidate to solve the problem without using dynamic programming for a brute force solution.