我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/maximal-rectangle/description/
题目描述:
知识点:栈、动态规划
思路:LeetCode084——柱状图中最大的矩形的变形
(1)对于二维数组matrix中的每一行,计算包括该行及该行之前所有行在内的1的高度。这个过程可以用动态规划来解决。
状态定义:
f(x, y)--------第x行第y列位置垂直方向上1的连续高度。
状态转移:
当x == 0时,f(x, y) = matrix(x, y) - '0'。这是第一行。
当x > 0时,如果matrix(x, y) == '0',则f(x, y) = 0。否则,f(x, y) = f(x - 1, y) + 1。
(2)对于每一行,将其看成是有高度的矩形,就是对于每一行求解LeetCode084——柱状图中最大的矩形的问题。
时间复杂度和空间复杂度均是O(m * n),其中m为matrix矩阵的行数,n为matrix矩阵的列数。
JAVA代码:
public class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if(m == 0){
return 0;
}
int n = matrix[0].length;
int[][] heights = new int[m][n];
for (int i = 0; i < n; i++) {
heights[0][i] = matrix[0][i] - '0';
}
for (int i = 1; i < m; i++) {
for (int j = 0; j < n; j++) {
if(matrix[i][j] == '0'){
heights[i][j] = 0;
}else{
heights[i][j] = heights[i - 1][j] + 1;
}
}
}
int result = 0;
for (int i = 0; i < m; i++) {
result = Math.max(result, maximalRectangle(heights[i]));
}
return result;
}
//LeetCode084
private int maximalRectangle(int[] heights){
int n = heights.length;
int[] newHeights = new int[n + 1];
for (int i = 0; i < n; i++) {
newHeights[i] = heights[i];
}
newHeights[n] = 0;
int result = 0;
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n + 1; i++) {
while(!stack.isEmpty() && newHeights[stack.peek()] >= newHeights[i]){
int index = stack.pop();
int left = stack.isEmpty() ? -1 : stack.peek();
result = Math.max(result, (i - left - 1) * newHeights[index]);
}
stack.push(i);
}
return result;
}
}
LeetCode解题报告: