085 Maximal Rectangle [Leetcode]
来源:互联网 发布:淘宝怎么看旺旺号 编辑:程序博客网 时间:2024/05/29 19:41
题目内容:
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
DP的过程还没有想清楚,先利用上一题的结果可以解决该问题。统计每一行为止向上有多少个连续的1做为bar的高度,对每一行调用Largest Rectangle in Histogram即可。
代码如下,运行时间32ms:
class Solution {public: int maximalRectangle(vector<vector<char>>& matrix) { if(matrix.size() == 0 || matrix[0].size() == 0) return 0; int row(matrix.size()), col(matrix[0].size()), result(0); vector<vector<int>> heights(row, vector<int>(col)); for(int i = 0; i < col; ++i) heights[0][i] = matrix[0][i] - '0'; result = largestRectangleArea(heights[0]); for(int i = 1; i < row; ++i) { for(int j = 0; j < col; ++j) { heights[i][j] = (matrix[i][j] - '0') ? heights[i-1][j] + 1 : 0; } int temp(largestRectangleArea(heights[i])); result = result > temp ? result : temp; } return result; } int largestRectangleArea(vector<int>& height) { if(height.size() == 0) return 0; //put a minimum number to calculate the area of last rectangle height.push_back(0); stack<int> h; int result(0), index(0), top(0); while(index < height.size()) { if(h.empty() || height[h.top()] < height[index]) { h.push(index++); } else { top = h.top(); h.pop(); //if stack had only 1 element, use index as width, else use current top index to calculate width top = h.empty() ? height[top] * index : height[top] * (index - h.top() - 1); result = result > top ? result : top; } } height.pop_back(); return result; }};
0 0
- LeetCode: Maximal Rectangle [085]
- 085 Maximal Rectangle [Leetcode]
- 【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
- 黑马程序员——Java基础--集合框架(1)
- C++标准库介绍
- 数据结构-队列1
- 简单 js 验证
- POJ 1000 A+B Problem
- 085 Maximal Rectangle [Leetcode]
- leetcode 21_Merge Two Sorted Lists & leetcode_258 Add Digits & leetcode_66plus one
- hdu1796 How many integers can you find 容斥原理
- GDOI2016模拟8.16总结
- HBase介绍
- UIViewConroller(控制器)间关系
- 蓝桥杯练习:入门训练 Fibonacci数列
- 超详细!iOS 并发编程之 Operation Queues
- 【算法】字符串包含