leetcode -- Maximal Rectangle TODO O(N)

时间:2021-08-01 16:53:16

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

[解题思路]

1.brute force

枚举所有sub-matrix(O(N^2), N = m*n) ,检查每个子矩阵是不是都是1,如果是更新最大面积,检查子矩阵是否都是1需要

花费O(N). 故总的时间为O(N^3) N = m*n

可以过小数据,大数据直接TLE

 public int maximalRectangle(char[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
int m = matrix.length;
if(m == 0){
return m;
}
int n = matrix[0].length;
if(n == 0){
return n;
} return generateMaxArea(matrix);
} private static int generateMaxArea(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int maxArea = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int subMatrixArea = enumerateSubMatrix(matrix, i, j);
if (subMatrixArea > maxArea) {
maxArea = subMatrixArea;
}
}
}
return maxArea;
} public static int enumerateSubMatrix(char[][] matrix, int i, int j) {
int m = matrix.length;
int n = matrix[0].length;
int subMatrixArea = 0;
for (int p = 0; p <= (m - i); p++) {
for (int q = 0; q <= (n - j); q++) {
int area = getSubMatrixArea(matrix, p, q, p + i - 1, q + j - 1);
if (area > subMatrixArea) {
subMatrixArea = area;
}
}
}
return subMatrixArea;
} private static int getSubMatrixArea(char[][] matrix, int p, int q, int i,
int j) {
for (int m = p; m <= i; m++) {
for (int n = q; n <= j; n++) {
if (matrix[m][n] == '0') {
return 0;
}
}
} return (i - p + 1) * (j - q + 1);
}

2.DP

令dp[i][j]表示点(i,j)开始向右连续1的个数,花费O(M*N)的时间可以计算出来

接着从每个点开始,将该点作为矩形左上角点,从该点开始向下扫描直到最后一行或者dp[k][j] == 0

每次计算一个矩形的面积,与最大面积进行比较,如最大面积小于当前面积则进行更新,总的时间复杂度为O(M*N*M)

 public int maximalRectangle(char[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
int m = matrix.length;
if(m == 0){
return m;
}
int n = matrix[0].length;
int[][] dp = new int[m][n]; for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == '0'){
continue;
} else {
dp[i][j] = 1;
int k = j + 1;
while(k < n && (matrix[i][k] == '1')){
dp[i][j] += 1;
k++;
}
}
}
}
int maxArea = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(dp[i][j] == 0){
continue;
} else{
int area = 0, minDpCol = dp[i][j];
for(int k = i; k < m && dp[k][j] > 0; k++){
if(dp[k][j] < minDpCol){
minDpCol = dp[k][j];
}
area = (k - i + 1) * minDpCol;
if(area > maxArea){
maxArea = area;
}
}
}
}
}
return maxArea;
}