zoukankan      html  css  js  c++  java
  • 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.

    Subscribe to see which companies asked this question.

    这题看起来和max square 是一样的题目,但是尝试用max square 的DP来做无法得出.主要是上一个右下角点定到的最大面积在下一次无法帮助相邻点直接得到最大rectangle. 3*4 == 2*6.

    实际如果使用DP解的话,是一个3维DP,f[i,j,k]对于坐标为i,j的点查找左上长为k的最大宽,之后进行转换.转换方程为:实际这题类似于Largest Rectangle in Histogram

    的做法,即对矩阵的每一行,纵向连续为1的地方朝上都形成了一个bar.每一行更新这个bar的高度的过程遵从DP, 每一行都求出一个最大的矩形面积.即循环调用单调递增栈解法.

    时间复杂度为O(m*n),空间复杂度为O(max(m,n))宽.栈和height的空间复杂度做一个比较,代码如下:

    class Solution(object):
        def maximalRectangle(self, matrix):
            """
            :type matrix: List[List[str]]
            :rtype: int
            """
            #f[i][j] must have height and width together
            if not matrix or not matrix[0]:
                return 0
            height = [int(n) for n in matrix[0]]
            maxRec = 0
            for i in xrange(0,len(matrix)):
                maxRec = max(maxRec, self.helper(matrix, height,i))
            return maxRec
                 
        def helper(self, matrix, height, i): #largest rectange higher or equal than this line
            stack = []
            area = 0
            for j in xrange(len(height)+1):
                curt = height[j] if j < len(height) else -1
                while stack and curt <= height[stack[-1]]:
                    h = height[stack.pop()]
                    w = j if not stack else j - stack[-1] - 1
                    area = max(area, h*w)
                stack.append(j)
            if i!= len(matrix)-1:
                for j in xrange(len(height)):
                    if matrix[i+1][j] == '1':
                        height[j] += 1
                    else:
                        height[j] = 0
            return area

  • 相关阅读:
    ListView具有多种item布局——实现微信对话列
    CSDN 2013年度博客之星评选——分享几张厦门杭州的美图
    不做旁观者,给博主最有力的支持——博客之星评选,期待您的支持,谢谢路过的朋友投上您宝贵的一票
    Android应用中使用及实现系统“分享”接口
    android手势创建及识别
    JSON数据源的多值参数实现
    葡萄城报表本地设计器
    如何设计带查询条件的报表
    巧用SQL语句补足不完全数据报表
    表格数据分组报表
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5591443.html
Copyright © 2011-2022 走看看