leetcode题 Maximal Rectangle
来源:互联网 发布:淘宝优惠券采集 编辑:程序博客网 时间:2024/05/16 19:24
题目要求:
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组成的2维矩阵,求数字全为1的最大矩形的面积。
一开始我的思路很单纯:分情况处理。
结果是:简单的情况都能很好的处理,唯独有一种情况——matrix[i-1][j-1],matrix[i][j-1],matrix[i-1][j]和matrix[i][j]都为1的情况,需要考虑很多。遇到这种特殊情况,最后的结果其实就是求某一点到[i][j]点包含‘1’的最大矩形,也就是求直方图的大小。这会儿发现前面的简单情况也可以归并到这个特殊情况。
求直方图的思路:从[i][j]遍历到[i][0],遇到不为0的位置[i][k]便停止,计算[i][k]和[i][j]构成的矩形大小S1,之后遍历[i-1][j]到[i-1][k],遇到不为0的位置[i-1][k1]停止,继续计算[i-1][k1]和[i][j]构成的矩形大小S2,与原来的S1比较,取最大。如此反复,直到遍历完矩阵。最后的S就是直方图面积。
有了当前点最大直方图的面积,原来的问题用一个简单地动态规划便可以解决(即将面积与S[i][j-1]和S[i-1][j]比较,取最大即可)。
public int currentArea(char[][] matrix, int x, int y) {int res=0;int endY = 0; for (int i = x; i >= 0; i--) {for (int j = y; j >=endY; j--) {if(matrix[i][j]=='0'){if((x-i+1)*(y-j)>res) res=(x-i+1)*(y-j);endY=j+1;break;}else{if(j==endY && (x-i+1)*(y-j+1)>res) res=(x-i+1)*(y-j+1);}} } return res;} public int maximalRectangle(char[][] matrix) { if(matrix.length<=0) return 0; int xLen = matrix.length; int yLen = matrix[0].length; int rectArea[][]=new int[xLen][yLen]; for (int i = 0; i < xLen; i++) {for (int j = 0; j < yLen; j++) {int max =currentArea(matrix, i, j);if(i>0 && rectArea[i-1][j]>max){max = rectArea[i-1][j];}if(j>0 && rectArea[i][j-1]>max){max = rectArea[i][j-1];}rectArea[i][j] = max;} } return rectArea[xLen-1][yLen-1]; }
0 0
- leetcode题 Maximal Rectangle
- 【LeetCode】Maximal Rectangle && Maximal Square
- Leetcode:Maximal Square & Maximal Rectangle
- [leetcode刷题系列]Maximal Rectangle
- LeetCode刷题笔录Maximal Rectangle
- LeetCode: Maximal Rectangle
- LeetCode Maximal Rectangle
- LeetCode: Maximal Rectangle
- [LeetCode] Maximal Rectangle
- [leetcode] Maximal Rectangle
- [LeetCode]Maximal Rectangle
- [leetcode]Maximal Rectangle
- LeetCode-Maximal Rectangle
- [leetcode] Maximal Rectangle
- Leetcode Maximal Rectangle
- [LeetCode] Maximal Rectangle
- leetcode Maximal Rectangle
- LeetCode Maximal Rectangle
- Swift语言中的switch语句的妙用
- Tools for Java programmers(2015)-1
- springMVC学习(注解实现依赖注入)
- Ubuntu下配置SVN服务器并在Win7下使用TortoiseSVN作为客户端
- 修改Eclipse默认workspace目录
- leetcode题 Maximal Rectangle
- 《php核心技术与最佳实践》笔记5
- 德国eheak汉科斯行车记录仪优势介绍!
- hdoj 2841 Visible Trees 【容斥原理】
- poj 3620 dfs 水
- 怎样改变小农经济思维
- MySQL之视图(View)
- Linux高级编程 第六章 进程控制 信号 定时器 信号操作 信号屏蔽
- 【codechef】Lazy Players