日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 85. 最大矩形(DP/单调递增栈,难)

發布時間:2024/7/5 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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;//返回最大面積} };

例子的求解過程如下:
數組

["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]

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題一致,行數變多了而已
class Solution { public:int maximalRectangle(vector<vector<char>>& mat) {if(mat.empty())return 0;int i, j, hi, width, maxarea = 0, m = mat.size(), n = mat[0].size();vector<int> h(n+1, 0);for(i = 0; i < m; ++i){stack<int> s;mat[i].push_back('0');//請看84題for(j = 0; j <= n; ++j){h[j] = mat[i][j]=='1' ? h[j]+1 : 0;//根據前一行,得到當前行的高while(!s.empty() && h[s.top()] > h[j]){hi = h[s.top()];s.pop();width = s.empty() ? j : j-s.top()-1;maxarea = max(maxarea, hi*width);}s.push(j);}}return maxarea;} };

總結

以上是生活随笔為你收集整理的LeetCode 85. 最大矩形(DP/单调递增栈,难)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。