【LeetCode】085. Maximal Rectangle
2024-08-28 05:03:47
题目:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6
题解:
这个题是在 Largest Rectangle in Histogram上的延伸,二维矩阵每一行为底,都可以看做一个直方图,输入矩阵有多少行,就可以形成多少个直方图,循环调用直方图最大面积函数即可。
Solution
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int res = ;
if(matrix.empty())
return res;
int n = matrix[].size();
vector<int> cals(n, );
for(int i = ; i < matrix.size(); ++i){
for(int j = ; j < n; ++j){
cals[j] = matrix[i][j] == '' ? : cals[j] + ;
}
res = max(res, maxRectangleArea(cals));
}
return res;
}
private:
int maxRectangleArea(vector<int> &nums){
int n = nums.size();
int res = , area = ;
nums.push_back();
stack<int> s;
for(int i = ; i <= n;){
if(s.empty() || nums[s.top()] <= nums[i])
s.push(i++);
else {
int cur = s.top(); s.pop();
area = nums[cur] * (s.empty() ? i : (i - s.top() - ));
res = max(res, area);
}
}
return res;
}
};
left数组表示左边界是1的位置,right数组表示右边界是1的位置,那么对于任意一行的第j个位置,矩形为(right[j] - left[j]) * height[j]
Solution 2 动态规划
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
int res = ;
if(matrix.empty())
return res;
int n = matrix[].size();
vector<int> height(n, ), left(n, ), right(n, n);
for(int i = ; i < matrix.size(); ++i){
int l = , r = n;
for(int j = ; j < n; ++j){
if(matrix[i][j] == ''){
++height[j];
left[j] = max(left[j], l);
} else {
l = j + ;
height[j] = ;
left[j] = ;
right[j] = n;
}
}
for(int j = n - ; j >= ; --j){
if(matrix[i][j] == ''){
right[j] = min(right[j], r);
res = max(res, height[j] * (right[j] - left[j]));
} else {
r = j;
}
}
}
return res;
}
};
最新文章
- tarjan讲解(用codevs1332(tarjan的裸题)讲解)
- linux命令-cp/scp {拷贝}
- WPF 4.0 DatePicker 快速录入
- C# 前台线程和后台线程
- 进程间通信机制<;转>;
- Android笔记之adb命令解析1
- 7.MVC框架开发(创建层级项目)
- 1242Rescue (优先队列BFS)
- 4、第4次课 CSS代码第三节课20150923
- C# ITextSharp pdf 自动打印
- SparkR安装部署及数据分析实例
- C++求出旋转数组的最小数字
- 【原创】分布式之redis复习精讲
- HTTP协议冷知识大全
- python笔记6-while、for循环
- 在Android开发中替换资源图片不起作用的解决方法
- LeetCode题解之Convert Sorted List to Binary Search Tree
- 2018.10.20 bzoj1068: [SCOI2007]压缩(区间dp)
- SQL Server查询已锁的表及解锁
- 怎么让一个div 悬浮在另一个div上
热门文章
- jquery 通过属性选择器获取input不为disabled的对象
- SVN流程图协作图
- 【BZOJ4070】[Apio2015]雅加达的摩天楼 set+最短路
- nginx访问日志中的时间格式修改
- 使用weka训练一个分类器
- What happens when we continue stacking deeper layers on a “plain” convolutional neural network?
- TensorFlow_action
- Surpassing Human-Level Face Verification Performance on LFW with GaussianFace
- 利用tomcatserver配置https双向认证
- Java进阶学习:JSON解析利器JackSon