题目:

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;
}
};

最新文章

  1. tarjan讲解(用codevs1332(tarjan的裸题)讲解)
  2. linux命令-cp/scp {拷贝}
  3. WPF 4.0 DatePicker 快速录入
  4. C# 前台线程和后台线程
  5. 进程间通信机制&lt;转&gt;
  6. Android笔记之adb命令解析1
  7. 7.MVC框架开发(创建层级项目)
  8. 1242Rescue (优先队列BFS)
  9. 4、第4次课 CSS代码第三节课20150923
  10. C# ITextSharp pdf 自动打印
  11. SparkR安装部署及数据分析实例
  12. C++求出旋转数组的最小数字
  13. 【原创】分布式之redis复习精讲
  14. HTTP协议冷知识大全
  15. python笔记6-while、for循环
  16. 在Android开发中替换资源图片不起作用的解决方法
  17. LeetCode题解之Convert Sorted List to Binary Search Tree
  18. 2018.10.20 bzoj1068: [SCOI2007]压缩(区间dp)
  19. SQL Server查询已锁的表及解锁
  20. 怎么让一个div 悬浮在另一个div上

热门文章

  1. jquery 通过属性选择器获取input不为disabled的对象
  2. SVN流程图协作图
  3. 【BZOJ4070】[Apio2015]雅加达的摩天楼 set+最短路
  4. nginx访问日志中的时间格式修改
  5. 使用weka训练一个分类器
  6. What happens when we continue stacking deeper layers on a “plain” convolutional neural network?
  7. TensorFlow_action
  8. Surpassing Human-Level Face Verification Performance on LFW with GaussianFace
  9. 利用tomcatserver配置https双向认证
  10. Java进阶学习:JSON解析利器JackSon