85. Maximal Rectangle

LeetCode题目:85. Maximal Rectangle

原题链接:https://leetcode.com/problems/maximal-rectangle/description/

解题思路:

核心思想:

  1. 84题的延伸

  2. 可以将每一行,看成一个直方图,值为0,代表直方图为0,值为1,代表直方图为n(n为该点向上数连续为1的个数)。举个例子,例图中转换的直方图为:

    第一行:[1, 0, 1, 0, 0]

    第二行:[2, 0, 2, 1, 1]

    第三行:[3, 1, 3, 2, 2]

    第四行:[4, 0, 0, 3, 0]

  3. 从例子中,我们可以看出生成直方图的方法。设x,y为下标,F(x, y)为x,y位置直方图的值,每行依次遍历,当该值为1时,F(x, y) = F(x - 1, y) + 1。当该值为0时,F(x, y) = 0。

  4. 最后,只要对每行执行84题中的程序,取最大值即可。

代码细节:

  1. 直方图用二维vector存储。

坑点:


代码:

#include <stack>
struct Matrix {
  int left;
  int index;
  int height;

  Matrix(int l, int i, int h) : left(l), index(i), height(h) {
  }
};

// 84 题目
int largestRectangleArea(vector<int>& heights) {
  if (heights.size() == 0)  return 0;

  stack<Matrix> sta;  // 用于计算的栈
  int maxSize = 0;            // 保存最大值
  int n = heights.size();     // size

  for (int i = 0; i < n; i++) {
    // 空栈,直接push
    if (sta.empty())  sta.push(Matrix(0, i, heights[i]));
    // 当高过栈顶时,直接push
    if (heights[i] >= sta.top().height)
      sta.push(Matrix(i, i, heights[i]));
    // 当低过栈顶时。计算栈顶,弹出,直到高过栈顶
    else {
      do {
        maxSize = max(maxSize, (i - sta.top().left) * sta.top().height);
        sta.pop();
      } while(!sta.empty() && heights[i] < sta.top().height);
      if (sta.empty())  sta.push(Matrix(0, i, heights[i]));
      else  sta.push(Matrix(sta.top().index + 1, i, heights[i]));
    }
  }

  // 清楚剩余空间
  while (!sta.empty()) {
    maxSize = max(maxSize, (n - sta.top().left) * sta.top().height);
    sta.pop();
  }

  return maxSize;
}

// 生成直方图集合
vector<vector<int>> geneHistograms(vector<vector<char>>& matrix) {
  vector<vector<int>> histograms;

  // 插入第一行
  if (!matrix.empty()) {
    vector<int> temp;
    for (int j = 0; j < matrix[0].size(); j++)
      temp.push_back(matrix[0][j] - '0');
    histograms.push_back(temp);
  }

  // 插入之后的行
  for (int i = 1; i < matrix.size(); i++) {
    vector<int> temp;
    for (int j = 0; j < matrix[0].size(); j++)
      if (matrix[i][j] == '0')  temp.push_back(0);
      else  temp.push_back(histograms[i - 1][j] + 1);
    histograms.push_back(temp);
  }

  return histograms;
}

int maximalRectangle(vector<vector<char>>& matrix) {
  vector<vector<int>> histograms;       // 直方图集合
  int maxSize = 0;                      // 最大值
  histograms = geneHistograms(matrix);

  // 将每条看成一个直方图
  for (int i = 0; i < histograms.size(); i++)
    maxSize = max(maxSize, largestRectangleArea(histograms[i]));

  return maxSize;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值