標籤:style blog http color io ar for div sp
Maximal Rectangle
Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing all ones and return its area.
解題分析:
聯想到 最大矩形面積 這一題,可以在O(n)時間內求出 最大的矩形面積
如果我們把每一行看成x座標,那高度就是從那一行開始往上數的1的個數。
利用 最大矩形面積 的方法,在O(n2)時間內就可以求出每一行形成的“柱狀圖”的最大矩形面積了
class Solution {public: int maximalRectangle(vector<vector<char> > &matrix) { int nRow = matrix.size(); if (nRow == 0) return 0; int nCol = matrix.at(0).size(); std::vector<int> tmp(nCol, 0); int result = 0; for (int i = 0; i < nRow; ++i) { // 計算每一行可以形成的最大矩形面積 for (int j = 0; j < nCol; ++j) { if (matrix.at(i).at(j) == ‘0‘) { tmp.at(j) = 0; } else { tmp.at(j)++; // 計算當前行的當前列的累積高度(1的個數) } } int area = largestRectangleArea(tmp); result = std::max(result, area); } return result; } // 最大矩形面積 int largestRectangleArea(std::vector<int>& height) { if (height.size() == 0) return 0; height.push_back(-1); std::stack<int> stk; int result = 0; for (int i = 0; i < height.size(); ) { if (stk.empty() || height.at(i) > height.at(stk.top())) { stk.push(i); ++i; } else { int idx = stk.top(); stk.pop(); int area = height.at(idx) * (stk.empty() ? i : i - stk.top() - 1); result = std::max(result, area); } } return result; }};
Leetcode:Maximal Rectangle 最大全1子矩陣