LeetCode-maximal-rectangle(最大矩阵面积)

题目描述

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

                                           LeetCode-maximal-rectangle(最大矩阵面积)_第1张图片

Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

 

                                          LeetCode-maximal-rectangle(最大矩阵面积)_第2张图片

The largest rectangle is shown in the shaded area, which has area =10unit.

For example,
Given height =[2,1,5,6,2,3],
return10.

算法思路:

请参考:https://blog.csdn.net/u012534831/article/details/74356851

class Solution {
public:
    int largestRectangleArea(vector &height) {
        int n=static_cast(height.size());
        if(n<=0) return 0;
        int ans=0,num;
        stackst;
        st.push(-1);
        for(int i=0;i

相同算法拓展:

题目描述

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

分别遍历每一行,将每次遍历的行及以上部分看做直方图求最大面积,最后遍历所有结果,求最大值。

class Solution {
public:
    int maximalRectangle(vector > &matrix) {
        int m=matrix.size();
        if(m<=0) return 0;
        int n=matrix[0].size();
        vectorh(n);
        fill(h.begin(),h.end(),0);
        int num;
        int ans=0;
        stackst;
        st.push(-1);
        for(int i=0;i

 

你可能感兴趣的:(LeetCode)