题目地址:Maximal Square - LeetCode
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
这道题目意思很容易懂,就是找出最大的正方形。
这道题目是我面XX时遇到的算法题。
根据Google | L3 | Seattle | Sep 2019 [No Offer] - LeetCode Discuss这篇文章,他在面谷歌时遇到了这道算法题。
最容易想到的就是暴力的方法,当然时间复杂度太高,肯定不被接受。
然后面试官提示我用动态规划,我就描述了一下我的算法。因为时间不够,面试官要吃饭去了,就没让我仔细解释。
Python解法如下:
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
result = 0
if matrix == []:
return result
height, width = len(matrix), len(matrix[0])
dp = []
for i in range(0, height + 1):
dp.append([0] * (width + 1))
for i in range(1, height + 1):
for j in range(1, width + 1):
if matrix[i-1][j-1]=='1':
dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]) + 1
result = max(dp[i][j], result)
return result ** 2
时间复杂度为O(nm),空间复杂度为O(mn)。
一般来说上面这个解法就可以了,但有空间复杂度为O(m)的更巧妙的解法。
Python解法如下:
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
result = 0
if matrix == []:
return result
height, width = len(matrix), len(matrix[0])
dp = [0] * (width + 1)
prev = 0
for i in range(1, height + 1):
for j in range(1, width + 1):
temp = dp[j]
if matrix[i - 1][j - 1] == '1':
dp[j] = min(dp[j - 1], prev, dp[j])+1
result = max(result, dp[j])
else:
dp[j] = 0
prev = temp
return result ** 2