30 Day Challenge Day 22 | Leetcode 85. Maximal Rectangle
题解
Hard
方法一:动态规划
取每个位置的最大高度 Maximum Height at Each Point
这道题与84题联系在一起看,完全可以转化成84题的样子。对于每一行,只看其以上的数组元素,把连续的值为1的格子累加起来,就变成 histogram 了。
那么,在每一个值为1的坐标位置上,找到对应的左边界、右边界和上边界(即高度)。遍历一遍,就得到当前数组的最大矩形了。
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;
int m = matrix.size();
int n = matrix[0].size();
vector<int> height(n, 0), left(n, 0), right(n, n-1);
int maxArea = 0;
for(int i = 0; i < m; i++) {
int cur_left = 0, cur_right = n-1;
// (1) update height[i] namely histogram
for(int j = 0; j < n; j++) {
if(matrix[i][j] == '1') {
height[j]++;
} else {
height[j] = 0;
}
}
// (2) update left[i]
for(int j = 0; j < n; j++) {
if(matrix[i][j] == '1') {
left[j] = max(left[j], cur_left);
} else {
left[j] = 0; // go back to left most
cur_left = j+1;
}
}
// (3) update right[i]
for(int j = n-1; j >= 0; j--) {
if(matrix[i][j] == '1') {
right[j] = min(right[j], cur_right);
} else {
right[j] = n-1; // go back to right most
cur_right = j-1;
}
}
// update maxArea
for(int j = 0; j < n; j++) {
maxArea = max(maxArea, (right[j]-left[j]+1)*height[j] );
}
}
return maxArea;
}
};
方法二:动态规划
借用84题Better Brute Force的方法,在这里是可以通过的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
int r = matrix.size();
if (r == 0) return 0;
int c = matrix[0].size();
// dp[i][j] := max len of all 1s ends with col j at row i.
vector<vector<int>> dp(r, vector<int>(c));
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
dp[i][j] = (matrix[i][j] == '1') ? (j == 0 ? 1 : dp[i][j - 1] + 1) : 0;
int ans = 0;
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
int len = INT_MAX;
for (int k = i; k < r; k++) {
len = min(len, dp[k][j]);
if (len == 0) break;
ans = max(len * (k - i + 1), ans);
}
}
return ans;
}
};