1. 程式人生 > 其它 >【LeetCode85】-最大矩形

【LeetCode85】-最大矩形

技術標籤:LeetCode刷題leetcode

實現思路:

這題實現的思路是建立 【LeetCode84】-柱狀圖中最大矩形面積基礎之上。

概括來說,解題過程就是遍歷每一行,將每一行及該行上面看成直方圖,在每一行計算該抽象直方圖最大的矩形面積即可。

構造每一行抽象直方圖的方法:判斷每一行的位置處是否為0,如果為0那麼直方圖對應的高度為0,否則高度為該行上一行的高度值加1

實現程式碼:

#include <iostream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
class Solution { public: int getMaxH(vector<int> heights) { int amax = 0; stack<int>s; s.push(-1); for (int i = 0;i < heights.size();i++) { while (s.top() != -1 && heights[s.top()] >= heights[i]) { int cur = s.top();s.pop(); amax = max(amax, heights[cur] *
(i - s.top() - 1)); } s.push(i); } while (s.top() != -1) { int cur = s.top();s.pop(); int area = heights[cur] * (heights.size() - s.top() - 1); amax = max(amax, area); } return amax; } int maximalRectangle(vector<vector<char>>& matrix) { int rows = matrix.
size(); if (rows == 0) return 0; int columns = matrix[0].size(); if (columns == 0) return 0; int amax = 0; vector<vector<int>> heights(rows,vector<int>(columns)); for (int i = 0;i < columns;i++) { heights[0][i] = matrix[0][i] == '0' ? 0 : 1; } for (int i = 1;i < rows;i++) { for (int j = 0;j < columns;j++) { heights[i][j] = matrix[i][j]=='0'?0: heights[i - 1][j] + 1; } } for (int i = 0;i < rows;i++) { amax = max(amax, getMaxH(heights[i])); } return amax; } }; int main() { return 0; }

提交結果:

在這裡插入圖片描述

總結:

這道題主要難在怎麼和之前直方圖求最大矩形結合再一起,以及如何構造抽象的直方圖,當理解這兩點之後,這道題解起來就十分容易了