"""
給定乙個僅包含 0 和 1 的二維二進位制矩陣,找出只包含 1 的最大矩形,並返回其面積。
示例:輸入:
[ ["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]輸出: 6
"""# 使用柱狀圖——棧
defmaximalrectangle
(matrix):if
not matrix:
return
0 m =
len(matrix)
n =len(matrix[0]
) maxarea =
0 dp =[0
]*nfor i in
range
(m):
for j in
range
(n):
dp[j]
= dp[j]+1
if matrix[i]
[j]==
'1'else
0 maxarea =
max(maxarea, area(dp)
)return maxarea
defarea
(heights)
: stack =[-
1]maxarea =
0for i in
range
(len
(heights)):
while stack[-1
]!=-1
and heights[stack[-1
]]>= heights[i]
: maxarea =
max(maxarea, heights[stack.pop()]
*(i-stack[-1
]-1)
)while stack[-1
]!=-1
: maxarea =
max(maxarea, heights[stack.pop()]
*(len(heights)
-stack[-1
]-1)
)return maxarea
# 動態規劃(每個點的最大高度)
defmaximalrectangle2
(matrix):if
not matrix:
return
0 m =
len(matrix)
n =len(matrix[0]
) left =[0
]*nright =
[n]*n
height =[0
]*nmaxarea =
0for i in
range
(m):
cur_left, cur_right =
0, n
#update height
for j in
range
(n):
if matrix[i]
[j]==
'1':
height[j]+=1
else
: height[j]=0
# update left
for j in
range
(n):
if matrix[i]
[j]==
'1':
left[j]
=max
(left[j]
, cur_left)
else
: left[j]=0
cur_left = j +
1# update right
for j in
range
(n-1,-
1,-1
):if matrix[i]
[j]==
'1':
right[j]
=min
(right[j]
, cur_right)
else
: right[j]
= n cur_right = j
# update the area
for j in
range
(n):
maxarea =
max(maxarea, height[j]
*(right[j]
-left[j]))
return maxarea
85 最大矩形
給定乙個僅包含 0 和 1 的二維二進位制矩陣,找出只包含 1 的最大矩形,並返回其面積。示例 輸入 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 輸出 6 方法 按層分割法 思路 按層生成從頭部開始,生成每一層的柱狀圖,然後求得改層的所能達到的最大面積,直到遍歷完...
85 最大矩形
高度更新的過程 邊界的更新 這種方法和常規的動態規劃有差別,沒有常規的dp矩陣定義。但是在行向下變化的時候,也是利用之前的狀態。class solution object def update self,i,j,dp length dp i j 0 height dp i j 1 area 0 fo...
85 最大矩形
題目 思路 這一題的演算法本質上和84題largest rectangle in histogram一樣,對每一行都求出每個元素對應的高度,這個高度就是對應的連續1的長度,然後對每一行都更新一次最大矩形面積。那麼這個問題就變成了largest rectangle in histogram。本質上是對...