【LeetCode】85. Maximal Rectangle【未完待续】

题目:

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

 

描述:

给出一个包含一位二进制数的矩阵,请求输出该矩阵中仅由1组成的最大矩阵所包含的1的个数

 

分析:

最直接思路:

对于一维的数组,如果求最大子串和,最快的算法是线性的,可以借用这个思想,快速判断某一行的两个位置之间是否全是1,

即只需要控制列的起点和终点即可,侥幸AC了, 不过只优于6%的提交者,可以再想想怎么优化

 

 

 

代码一:(时间复杂度O(m*n^2),n,m 分别为矩阵的行和列)

class Solution {
public:
	int maximalRectangle(vector<vector<char>>& matrix) {
		if (!matrix.size() || !matrix[0].size()) {
			return 0;
		}
		for (int i = 0; i < matrix.size(); ++ i) {
			matrix[i][0] -= '0';
			for(int j = 1; j < matrix[0].size(); ++ j) {
				matrix[i][j] = matrix[i][j] - '0' + matrix[i][j - 1];
			}
		}
		int result = 0;
		for (int i = 0; i < matrix[0].size(); ++ i) {
			for (int j = i; j < matrix[0].size(); ++ j) {
				caculate(matrix, i, j, result);
			}
		}
		return result;
	}
	void caculate(const vector<vector<char>>& matrix, int col_begin, int col_end, int &result) {
		int temp = 0, count = col_end - col_begin + 1;
		for (int i = 0; i < matrix.size(); ++ i) {
			int last_sum = 0;
			if (col_begin) {
				last_sum = matrix[i][col_begin - 1];
			}
			temp += count;
			int dis = matrix[i][col_end] - last_sum;
			if (dis != count) {
				temp = 0;
			}
			result = max(result, temp);
		}
	}
};

 

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页