LeetCode 85. 最大矩形(DP/单调递增栈,难)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 85. 最大矩形(DP/单调递增栈,难)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
- 2.1 DP
- 2.2 單調遞增棧
1. 題目
給定一個僅包含 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) 鏈接:https://leetcode-cn.com/problems/maximal-rectangle
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
類似題目:
LeetCode 221. 最大正方形(DP)
LeetCode 84. 柱狀圖中最大的矩形(單調遞增棧)
2.1 DP
參考官方的解題思路:
class Solution { public:int maximalRectangle(vector<vector<char>>& mat) {if(mat.empty())return 0;int i, j, minL, maxR, maxarea = 0;int r = mat.size(), c = mat[0].size();vector<vector<int>> left(r,vector<int>(c,0));vector<vector<int>> right(r,vector<int>(c,c));vector<vector<int>> height(r,vector<int>(c,0));for(i = 0; i < r; i++) {//填寫left,相連的1,先到最高,然后最左側的下標minL = 0;for(j = 1; j < c; j++){if(i == 0)//第一行{if(mat[i][j] == '1'){if(mat[i][j-1] == '0')minL = j;//左邊0,當前1,需要更新最左邊的邊界minLleft[i][j] = minL;}}else//剩余行{if(mat[i][j] == '1'){if(mat[i][j-1] == '0')minL = j;left[i][j] = max(minL,left[i-1][j]);//跟上面的行,比較,取大}}}maxR = c;for(j = c-2; j >= 0; j--){if(i == 0)//第一行{if(mat[i][j] == '1'){if(mat[i][j+1] == '0')maxR = j+1;//右邊0,當前1,更新最右邊的邊界maxRright[i][j] = maxR;}}else//其余{if(mat[i][j] == '1'){if(mat[i][j+1] == '0')maxR = j+1;right[i][j] = min(maxR,right[i-1][j]);//還要更上面的比較,取小}}}for(j = 0; j < c; j++){if(i == 0)//第一行{if(mat[i][j] == '1')height[i][j] = 1;}else//剩余{if(mat[i][j] == '1')height[i][j] = 1+height[i-1][j];}}for(j = 0; j < c; j++)maxarea = max(maxarea, (right[i][j]-left[i][j])*height[i][j]);}return maxarea;//返回最大面積} };例子的求解過程如下:
數組
left
[0 0 2 0 0][0 0 2 2 2][0 0 2 2 2][0 0 0 3 0]right
[1 5 3 5 5][1 5 3 5 5][1 5 3 5 5][1 5 5 4 5]height
[1 0 1 0 0][2 0 2 1 1][3 1 3 2 2][4 0 0 3 0]area
[1 0 1 0 0][2 0 2 3 3][3 5 3 6 6][4 0 0 3 0]2.2 單調遞增棧
- 思路跟84題一致,行數變多了而已
總結
以上是生活随笔為你收集整理的LeetCode 85. 最大矩形(DP/单调递增栈,难)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1333. 餐厅过滤器
- 下一篇: 程序员面试金典 - 面试题 17.08.