1. 程式人生 > >Leetcode 85:最大矩形(超詳細的解法!!!)

Leetcode 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

解題思路

這個問題實際上就是之前Leetcode 84:柱狀圖中最大的矩形(超詳細的解法!!!)問題的拓展。我們可以將這個問題轉化為之前的那個問題,也就是我們將此時輸入矩陣的每一行以上的所有行看成是一個柱狀圖。

我們最後會得到上面這個直方圖矩陣。

class Solution:
    def maximalRectangle(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix:
            return 0
        
        r, c = len(matrix), len(matrix[0])
        height, res = [0]*c, 0
        for row in matrix:
            for
i in range(c): height[i] = height[i] + 1 if row[i] == '1' else 0 res = max(self.helper(height), res) return res def helper(self, row): stack = list() len_row, i = len(row), 0 res = 0 while i < len_row: if
not stack or row[stack[-1]] <= row[i]: stack.append(i) i += 1 else: k = stack.pop() res = max(res, row[k]*((i-stack[-1]-1) if stack else i)) while stack: k = stack.pop() res = max(res, row[k]*((i-stack[-1]-1) if stack else i)) return res

非常酷!!!我們可以將上述的程式碼繼續簡化(參考之前問題的最後一種寫法)

class Solution:
    def maximalRectangle(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix:
            return 0
        
        r, c = len(matrix), len(matrix[0])
        height, res = [0]*(c+1), 0
        for row in matrix:
            for i in range(c):
                height[i] = height[i] + 1 if row[i] == '1' else 0
            
            stack = [-1]
            for idx, val in enumerate(height):
                while val < height[stack[-1]]:
                    h = height[stack.pop()]
                    res = max(res, h*(idx - stack[-1] - 1))
                    
                stack.append(idx)
                
        return res

reference:

https://leetcode.com/problems/maximal-rectangle/discuss/29065/AC-Python-DP-solutioin-120ms-based-on-largest-rectangle-in-histogram

我將該問題的其他語言版本新增到了我的GitHub Leetcode

如有問題,希望大家指出!!!