Description
Given a rows x cols binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Examples
Example 1:
Input: matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = []
Output: 0
Example 3:
Input: matrix = [[“0”]]
Output: 0
Example 4:
Input: matrix = [[“1”]]
Output: 1
Example 5:
Input: matrix = [[“0”,“0”]]
Output: 0
Constraints:
rows == matrix.length
cols == matrix[i].length
0 <= row, cols <= 200
matrix[i][j] is ‘0’ or ‘1’.
Solution
这道题我一开始也想着用动态规划做的!!(和动态规划过不去了),但状态转移式子一直都搞不好,会有酱酱酿酿的特殊情况
所以还是简简单单,先计算每一排所有的Max_height,再将它转换为#84比较好(lc也是用心了,把这两题放在一起)
(甚至直接用了上一题的代码没有重新写
代码
class Solution {
public int largestRectangleArea(int[] heights) {
int answer = 0;
int[] position = new int[heights.length];
int i, j;
for(i = 0; i < heights.length; i++){
if(i > 0 && heights[i] == heights[i - 1]){
position[i] = position[i - 1];
continue;
}
int temp = heights[i];
for(j = i - 1; j >= 0; j--){
if (heights[i] > heights[j])
break;
else
j = position[j] + 1;
}
position[i] = j;
temp = temp + (i - j - 1) * heights[i];
for(j = i + 1; j < heights.length; j++){
if (heights[i] > heights[j])
break;
}
temp = temp + (j - i - 1) * heights[i];
if(answer < temp)
answer = temp;
}
return answer;
}
public int maximalRectangle(char[][] matrix) {
int row = matrix.length;
if(row == 0)
return 0;
int col = matrix[0].length;
int[] height = new int[col];
int answer = 0;
int i, j;
for(i = 0; i < col; i++){
height[i] = matrix[0][i] - '0';
}
answer = Math.max(answer, largestRectangleArea(height));
for(i = 1; i < row; i++){
for(j = 0; j < col; j++){
if(matrix[i][j] == '0'){
height[j] = 0;
continue;
}
height[j] = height[j] + 1;
}
answer = Math.max(answer, largestRectangleArea(height));
}
return answer;
}
}