49、最大矩形
程序员文章站
2022-03-17 20:51:11
...
题目描述:
使用动态规划,看代码:
class Solution {
public int maximalRectangle(char[][] matrix) {
int row = matrix.length;
if(row == 0){
return 0;
}
int col = matrix[0].length;
int[][] dp = new int[row][col];
boolean flag = false;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == '0') {
dp[i][j] = 0;
} else {
flag = true;
if (j == 0) {
dp[i][j] = 1;
continue;
}
dp[i][j] = dp[i][j - 1] + 1;
}
}
}
if (!flag) {
return 0;
}
int max = 1;
for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
int width = dp[i][j];
int length = 1;
max = Math.max(max,length * width); //注意:需要首先计算行是1,对应的面积
if (dp[i][j] == 0) {
continue;
}
for (int k = i - 1; k >= 0; k--) {
if(dp[k][j] == 0){
break;
}
length ++;
width = Math.min(width, dp[k][j]);
max = Math.max(max,length * width);
}
}
}
return max;
}
}
上一篇: 什么是SQL注入?
下一篇: 或许你不知的ORACLE秘密 系列一