LeetCode85——Maximal Rectangle
2016-01-28 20:44
363 查看
LeetCode85——Maximal Rectangle
初看这道题有点不知所措,但是其实是LeetCode84——Largest Rectangle in Histogram的一个变形。
原题
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.意思是在一个二维0-1矩阵中,找出包含1最多的全1矩形。
分析
想起LeetCode84——Largest Rectangle in Histogram这题,其实把矩阵从某一行横切,假设上半部分为柱状图,则只要从第0行到第n-1行每一行切一次,就会有n个不同柱状图,每个柱状图求最大矩形,最后复杂度为O(n∗m),n和m分别为矩阵的行和列。关于生成柱状图,因为我们已经知道从row-1行切开生成的柱状图的“形状”,对于row行来说,如果matrix[row][j]==’0’说明该行与上一行脱节了,不能将其计算进入矩形,所以直接另该列高度为0,否则该列高度为上一行的高度加1。
heights[j] = matrix[row][j] == '0' ? 0 : (heights[j] + 1);
代码
class Solution { private: //按行生成柱状图 void createHistogram(const vector<vector<char>>& matrix, vector<int>&heights, int row) { int col = matrix[0].size();//列 for (int j = 0; j < col; j++) { heights[j] = matrix[row][j] == '0' ? 0 : (heights[j] + 1); } } public: int maximalRectangle(vector<vector<char>>& matrix) { if (matrix.size() == 0 || matrix[0].size() == 0) return 0; vector<int>heights(matrix[0].size() + 1);//init int maxRow = matrix.size(); int maxSize = 0; //int rowSize = 0; //对每一行使用上一题的算法 for (int row = 0; row < maxRow; row++) { createHistogram(matrix, heights, row);//生成柱状图 stack<int>index; int i = 0; while (i < heights.size()) { if (index.empty() || heights[i] > heights[index.top()]) { index.push(i); ++i; } else { int j = index.top(); index.pop(); maxSize = max(maxSize, heights[j] * (index.empty() ? i : (i - index.top() - 1))); } } } return maxSize; } };
相关文章推荐
- java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x1
- ps
- maven-dependency-plugin插件的使用
- 叙旧(五)
- 图片压缩尺寸,本地沙盒缓存,上传服务器
- Docker Registry V1 与 V2 的区别解析以及灵雀云的实时同步迁移实践
- LeetCode 80. Remove Duplicates from Sorted Array II
- CentOS下yum使用代理的设置
- VS2010 C++ 操作Excel表格的编程实现
- CentOS下yum使用代理的设置
- 数据结构:JavaScript实现栈
- PyQt学习笔记02-drag & drop
- android之浮动title
- struts2动态方法调用(DMI)
- python的搜索路径与包(package)
- NYOJ 1003 MAX SUM
- Android中自定义一个事件监听器
- 性能优化过度绘制
- linux 信号 可重入函数
- 详细讲解transform,一看就懂了!