85. Maximal Rectangle
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 6.
解法1:看了半天的discuss,不得不说动态规划的思想真的很难搞。看懂之后就觉得也没想象那么难,但是为什么自己想不到呢,还是因为做题不多的原因吧,作者链接:https://discuss.leetcode.com/topic/6650/share-my-dp-solution
计算面积的公式:(right[i,j]-left[i,j])*height[i,j] 左右边界是左闭右开的。
left(i,j) = max(left(i-1,j), cur_left), cur_left can be determined from the current row //left 主要是记录当前高度下最左的边
right(i,j) = min(right(i-1,j), cur_right), cur_right can be determined from the current row //right主要是记录当前高度最右边+1
height(i,j) = height(i-1,j) + 1, if matrix[i][j]=='1'; //height记录从上往下连续的1的个数
height(i,j) = 0, if matrix[i][j]=='0' 。
class Solution { public: int maximalRectangle(vector<vector<char>>& matrix) { if(matrix.empty())return 0; int n=matrix.size(); int m=matrix[0].size(); int left[m],right[m],height[m],ans=0; // fill_n(left,m,0),fill_n(right,m,m),fill_n(right,m,0); fill(left,left+m,0),fill(right,right+m,m),fill(height,height+m,0); for(int i=0;i<n;i++){ int cur_left=0,cur_right=m; for(int j=0;j<m;j++){ if(matrix[i][j]=='0')height[j]=0; else height[j]++; } for(int j=0;j<m;j++){ if(matrix[i][j]=='0')cur_left=j+1,left[j]=0; else left[j]=max(left[j],cur_left); } for(int j=m-1;j>=0;j--){ if(matrix[i][j]=='0')cur_right=j,right[j]=m; else right[j]=min(right[j],cur_right); } for(int j=0;j<m;j++){ // printf("left:%d right:%d height:%d\n",left[j],right[j],height[j]); ans=max(ans,(right[j]-left[j])*height[j]); } } return ans; } };
解法2:参照Largest Rectangle in Histogram的思路,前者是计算给定高度排列的最大矩形面积,此处只要每行遍历过去,从该行往上连续的1就是前者题目的高度。
class Solution { public: int largestRectangleArea(vector<int>& heights) { heights.push_back(0); int n=heights.size(),area=0; stack<int>s; for(int i=0;i<n;i++){ if(s.empty()||heights[i]>=heights[s.top()])s.push(i); else { int top=s.top(); s.pop(); area=max(area,heights[top]*(s.empty()?i:i-s.top()-1)); i--; } } return area; } int maximalRectangle(vector<vector<char>>& matrix) { if(matrix.empty())return 0; int n=matrix.size(); int m=matrix[0].size(); int ans=0; vector<int>heights(m,0); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(matrix[i][j]=='0')heights[j]=0; else heights[j]++; } ans=max(ans,largestRectangleArea(heights)); } return ans; } };