欢迎访问LeetCode题解合集
题目描述
在一个由 '0'
和 '1'
组成的二维矩阵内,找到只包含 '1'
的最大正方形,并返回其面积。
示例 1:
[HTML_REMOVED]
[HTML_REMOVED]
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
示例 2:
[HTML_REMOVED]
[HTML_REMOVED]
输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:
输入:matrix = [["0"]]
输出:0
提示:
-
m == matrix.length
-
n == matrix[i].length
-
1 <= m, n <= 300
-
matrix[i][j]
为'0'
或'1'
题解:
动态规划。
设 f[i][j]
表示以 (i,j)
为正方形右下角,只包含 1
的正方形的变长最大值。
转移方程:
- 如果
i == 0 || j == 0
,f[i][j] = matrix[i][j] - '0'
- 如果
matrix[i][j] == '0'
,f[i][j] = 0
- 否则的话,
f[i][j] = min{f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]} + 1
时间复杂度:$O(n^2)$
额外空间复杂度:$O(n^2)$
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> f(n, vector<int>(m));
int ret = 0;
for ( int i = 0; i < n; ++i ) {
for ( int j = 0; j < m; ++j ) {
if ( !i || !j )
f[i][j] = matrix[i][j] & 15;
else if ( matrix[i][j] == '0' )
f[i][j] = 0;
else
f[i][j] = min( {f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]} ) + 1;
ret = max( ret, f[i][j] );
}
}
return ret * ret;
}
};
/*
时间:28ms,击败:75.32%
内存:11.2MB,击败:74.87%
*/
使用滚动数组优化:
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<int> f(m);
int ret = 0;
for ( int i = 0; i < m; ++i ) {
f[i] = matrix[0][i] & 15;
ret |= f[i];
}
int pre, tmp;
for ( int i = 1; i < n; ++i ) {
pre = f[0];
f[0] = matrix[i][0] & 15;
if ( f[0] && !ret ) ret = 1;
for ( int j = 1; j < m; ++j ) {
tmp = f[j];
if ( matrix[i][j] == '0' )
f[j] = 0;
else
f[j] = min( {f[j], f[j - 1], pre} ) + 1;
pre = tmp;
ret = max( f[j], ret );
}
}
return ret * ret;
}
};
/*
时间:24ms,击败:91.69%
内存:10.5MB,击败:98.54%
*/