方法1: 这道题目太难了,超出了我的能力。这道题本应该是dp,但是dp好像很烦,我都没去看。但是我看到了一个还不错的解答,就是把这道题转换为第84题。下面我给出链接,看这个人的评论
下面展示这种解法的代码,复杂度没分析,没精力了。复盘的时候自己分析复杂度,并且要把dp解答也弄明白。
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix.length == 0) return 0;
int n = matrix[0].length;
int[] heights = new int[n]; // using a array to reduce counting step of 1
int max = 0;
for(char[] row: matrix){
for(int i = 0; i < n; i++){
if(row[i] == '1'){
heights[i] += 1;
} else {
heights[i] = 0;
}
}
max = Math.max(max, maxArea(heights)); // go a sub problem of Histogram
}
return max;
}
// Exact same solution to Histogram
public int maxArea(int[] heights){
Stack<Integer> stack = new Stack();
int max = 0;
for(int i = 0; i <= heights.length; i++){
int h = (i == heights.length) ? 0 : heights[i];
while(!stack.isEmpty() && heights[stack.peek()] > h){
int index = stack.pop();
int leftBound = -1;
if(!stack.isEmpty()){
leftBound = stack.peek();
}
max = Math.max(max, heights[index] * (i - leftBound - 1));
}
stack.push(i);
}
return max;
}
}
总结:
- 无