Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
应用直方图找矩形的函数 将每一行每一位上方的1的个数化为直方图,面积最大的矩形即都为1且面积最大的矩形
class Solution { public: int largestRectangleArea(vector<int> &height) { if(height.size()==0)return 0; stack<pair<int,int> > sta; pair<int,int> p,q; int max=0; int start,end,area; for(int i=0;i<height.size();i++){ p.first=height[i]; p.second=i; if(sta.size()==0){ sta.push(p); } else{ while(sta.top().first>p.first){ q=sta.top(); sta.pop(); end=i-1; if(sta.size()==0){ start=0; area=q.first*(end-start+1); if(area>max)max=area; break; } else{ start=sta.top().second+1; area=q.first*(end-start+1); if(area>max)max=area; } } if(sta.size()!=0){ if(sta.top().first==p.first){ sta.top().second=i; } else{ sta.push(p); } } else{ sta.push(p); } } } end=height.size()-1; while(sta.size()!=0){ q=sta.top(); sta.pop(); if(sta.size()==0){ start=0; area=q.first*(end-start+1); if(area>max)max=area; } else{ start=sta.top().second+1; area=q.first*(end-start+1); if(area>max)max=area; } } return max; } int maximalRectangle(vector<vector<char> > &matrix) { // Note: The Solution object is instantiated only once and is reused by each test case. if(matrix.size()==0||matrix[0].size()==0){ return 0; } vector<int> histogram; histogram.resize(matrix[0].size(),0); int max=0; for(int i=0;i<matrix.size();i++){ for(int j=0;j<matrix[i].size();j++){ if(matrix[i][j]=='1')histogram[j]++; else histogram[j]=0; } int v=largestRectangleArea(histogram); if(v>max)max=v; } return max; } };