方法一:动态规划
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix:return 0
m = len(matrix)
n = len(matrix[0])
res = 0
dp = [[0]*(n) for _ in range(m)]
for i in range(m):
for j in range(n):
if(matrix[i][j] == "1"):
dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1
res = max(dp[i][j], res)
return res*res
方法二:动态规划+空间优化
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix :return 0
m = len(matrix)
n = len(matrix[0])
res = 0
pre = 0
dp = [0]*(n+1)
for i in range(m):
for j in range(1,n+1):
tmp = dp[j]
if(matrix[i][j-1]=="1"):
dp[j] = min(pre, dp[j-1],dp[j]) + 1
res = max(dp[j], res)
else:
dp[j] = 0
pre = tmp
pre = 0
return res*res