Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
算法
对于matrix[i][j],考虑以它为右下角的矩形。
遍历每一行,用最后出现的0来计算宽度. 想得时候没问题,写的时候忘了宽度要取最小值,以后最好是先写好递推式或者pseudo code。
dp[i][j]表示第i行不超过第j列的最后一个0出现的位置
[code]
public class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix==null || matrix.length==0 || matrix[0].length==0)return 0;
int m=matrix.length, n=matrix[0].length;
int dp[][]=new int [m][n];
int max= dp[0][0]==0 ? 0: 1;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j]=='0')
{
dp[i][j]=j;
}
else
{
dp[i][j]= j==0 ? -1 : dp[i][j-1];
max=Math.max(max,j-dp[i][j]);
int k=i-1, len=j-dp[i][j];
while(k>=0 && dp[k][j]<j)
{
len=Math.min(len,j-dp[k][j]);
max=Math.max(max, (i-k+1)*len);
k--;
}
}
}
}
return max;
}
}