Leetcode Maximal Rectangle
来源:互联网 发布:ember.js pdf 编辑:程序博客网 时间:2024/05/19 20:37
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 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 6. 这道题目难度略大,hard的题目还是有点意思的。虽然想到了用动态规划大法,但没有找到解决该题的思路。看了别人代码才找到思路。矩形的面积由长和高共同决定,而矩形的长和高需要分别使用动态规划大法来确定。跟前前一行记录的信息状态以及当前行的状态来进行计算。在实现的时候使用了一些技巧,通过向量来记录前一行的状态信息,然后再将当前行的状态信息写入向量,从而有效节省空间。
状态转移方程:
if matrix[i][j] == '1' left[i][j] = max(left[i-1][j],cur_left) else left[i][j] = 0, cur_left = j+1;
if matrix[i][j] == '1' right[i][j] = min(right[i-1][j],cur_right) else right[i][j] = n,cur_right = j;
if matrix[i][j] == '1' height[i][j]++ else height[i][j] = 0
if( max < (right[i][j] -left[i][j])*height[i][j])) max =(right[i][j] -left[i][j])*height[i][j])
代码如下:
class Solution {public:int maximalRectangle(vector<vector<char> > &matrix) { if(matrix.empty()) return 0; int m = matrix.size(); int n = matrix[0].size(); int left[n], right[n], height[n]; memset(left,0,sizeof(int)*n); for(int i=0;i<n;i++) right[i] = n; memset(height,0,sizeof(int)*n); int result = 0; for(int i=0; i<m; i++) { int cur_left=0, cur_right=n; for(int j=0; j<n; j++) { if(matrix[i][j]=='1') { left[j]=max(left[j],cur_left); height[j]++; } else { left[j]=0; cur_left=j+1; height[j]=0; } } for(int j=n-1; j>=0; j--) { if(matrix[i][j]=='1') right[j]=min(right[j],cur_right); else {right[j]=n; cur_right=j;} } for(int j=0; j<n; j++) result = max(result,(right[j]-left[j])*height[j]); } return result; }};
- 【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
- [Leetcode] Maximal Rectangle (Java)
- 162. Find Peak Element
- “云中观世界”之二:视觉智能生态
- Servlet 知识点(三) -- Servlet 的文件上传功能导致后台取值失败
- 如何做好系统测试
- JS-创建对象的七中方式
- Leetcode Maximal Rectangle
- Android 应用内某些页面禁止截屏与截屏工具类
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析]
- B.FRIENDit壁虎忍者专业电竞座椅 家用办公椅 电脑电竞防驼背护腰护颈椅子黄黑色
- Spark DataFrame和Dataset区别
- Dynamics CRM2016 Subgrid之OnLoad event
- Android BroadcastReceiver
- git reset --hard HEAD^ more?
- 可能用到的数据集记录