思路
借鉴84题,随着行数的的累加,在每一行都计算高度,然后运用单调栈的方法进行最大矩形的计算。
注意在每一行计算高度时,如果当前元素为0,那么高度一定要置0,如果为1,那么就是每一行的累加高度再+1
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
res = 0
r = len(matrix)
c = len(matrix[0])
h = [0] * (c + 1)
for i in range(r):
stack = [-1]
for j in range(c):
if matrix[i][j] == '1':
h[j] += 1
else:
h[j] = 0
for j in range(len(h)):
while stack and h[j] < h[stack[-1]]:
top = stack.pop()
res = max(res,h[top] * (j - stack[-1] - 1))
stack.append(j)
return res
return res
其实就是在每一行进行高度数组的叠加后,寻找高度数组中,每一个数左右比他小的数的最近位置。
可以用单调栈进行解决
class Solution:
def maximalRectangle(self, matrix):
if not matrix:
return 0
row = len(matrix)
col = len(matrix[0])
h = [0] * col
res = 0
for i in range(row):
for j in range(col):
if matrix[i][j] == '1':
h[j] += 1
else:
h[j] = 0
# print(h)
#找每个数左右距离他最近的比他小的数的位置(注意存在重复数)
dp = [[0,0] for _ in range(col)] #保存每个位置左右比他小的最近的数的位置
stack = [] #单调栈
for j in range(len(h)):
while stack and h[j] < h[stack[-1][0]]: #小于栈顶元素就弹出栈顶元素
tmp = stack.pop()
for x in tmp:
dp[x][0] = stack[-1][-1] if stack else -1
dp[x][1] = j
if stack and h[j] == h[stack[-1][0]]: #相等就放到栈中最后一个list中
stack[-1].append(j)
else:
stack.append([j])
while stack:
tmp = stack.pop()
for x in tmp:
dp[x][0] = stack[-1][-1] if stack else -1
dp[x][1] = col
# print(stack)
# print(dp)
res = max(res,max(h[j] * (dp[j][1] - dp[j][0] - 1) for j in range(len(h))))
return res