链接:https://leetcode-cn.com/problems/maximal-square/
代码:
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: m = len(matrix) if m == 0: return 0 res = -1 n = len(matrix[0]) dp = [[0] * n for _ in range(m)] if n == 0: return 0 for i in range(m): for j in range(n): if matrix[i][j] == '1': if i == 0 or j == 0: dp[i][j] = 1 else: dp[i][j] = min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1 res = max(res, dp[i][j]) return res*res
思路:dp[i,j]表示以 matrix[i,j]为右下角的最大的正方形的边长。dp[i,j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1,是由左,上,左上转移来的,一定要记住 dp 是又同等性质不同规模的子问题转移过来,通过记录子问题状态来达到节省时间的目的(不用每到一个点就重复算子问题了)