题目链接:https://leetcode.com/problems/maximal-rectangle/
思路:先用DP转化成每一行的直方图,再利用84题的思路逐行求解出最后的结果。
如下图所示:
如果我们把每一行看成x坐标,那高度就是从那一行开始往上数的1的个数。
带入我们的largestRectangleArea方法,在O(n2)时间内就可以求出每一行形成的“柱状图”的最大矩形面积了。
总的时间复杂度为O(n3).
对84题思路不清楚的看这里。
AC 30ms Java:
class Solution {
public int maximalRectangle(char[][] matrix) {
int m=matrix.length;
if(m==0)
return 0;
int n=matrix[0].length;
int[][] height=new int[m][n];
int max=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]=='0')
height[i][j]=0;
else
height[i][j]=(i==0)?1:height[i-1][j]+1;
}
int temp=largestRectangleArea(height[i]);
max=Math.max(max,temp);
}
return max;
}
public int largestRectangleArea(int[] heights) {
int maxArea=0;
int[] array=new int[heights.length+1];
for(int i=0;i<heights.length;i++){
array[i]=heights[i];
}
for(int i=0;i<array.length-1;i++){
if(array[i]<=array[i+1])
continue;
int low=array[i];
for(int j=i;j>=0;j--){
low=Math.min(low,array[j]);
int area=low*(i-j+1);
maxArea=Math.max(maxArea,area);
}
}
return maxArea;
}
}