Leetcode之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——递归,比较慢

   int maximalRectangle(vector<vector<char> > &matrix) {
        int res = 0;
        vector<int> height;
        for (int i = 0; i < matrix.size(); ++i) {
            height.resize(matrix[i].size());
            for (int j = 0; j < matrix[i].size(); ++j) {
                height[j] = matrix[i][j] == '0' ? 0 : (1 + height[j]);
            }
            res = max(res, largestRectangleArea(height));
        }
        return res;
    }
    int largestRectangleArea(vector<int> &height) {
        int res = 0;
        stack<int> s;
        height.push_back(0);
        for (int i = 0; i < height.size(); ++i) {
            if (s.empty() || height[s.top()] <= height[i]) s.push(i);
            else {
                int tmp = s.top();
                s.pop();
                res = max(res, height[tmp] * (s.empty() ? i : (i - s.top() - 1)));
                --i;
            }
        }
        return res;
    }

2——遍历,比较快

int largestRectangleArea(vector<int> &height) {
	int res = 0;
	stack<int> s;
	height.push_back(0);
	for (int i = 0; i < height.size(); ++i) {
		if (s.empty() || height[s.top()] <= height[i]) s.push(i);
		else {
			int tmp = s.top();
			s.pop();
			res = max(res, height[tmp] * (s.empty() ? i : (i - s.top() - 1)));
			--i;
		}
	}
	return res;
}
int maximalRectangle(vector<vector<char> > &matrix) {
	int res = 0;
	vector<int> height;
	for (int i = 0; i < matrix.size(); ++i) {
		height.resize(matrix[i].size());
		for (int j = 0; j < matrix[i].size(); ++j) {
			height[j] = matrix[i][j] == '0' ? 0 : (1 + height[j]);
		}
		res = max(res, largestRectangleArea(height));
	}
	return res;
}

想法:

勤动脑,多思考!

猜你喜欢

转载自blog.csdn.net/qq_35455503/article/details/89548025