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
posted on 2016-06-16 16:35 Sheryl Wang 阅读(231) 评论(0) 编辑 收藏 举报