Leetcode:Maximal Rectangle 最大全1子矩陣

來源:互聯網
上載者:User

標籤: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子矩陣

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.