leetcode之Largest Rectangle in Histogram、Maximal Rectanglex;待字闺中之最大矩形分析

本文介绍了两种算法:求直方图中最大矩形面积(Largest Rectangle in Histogram)及二维矩阵中全为1的最大矩形(Maximal Rectangle)。通过动态规划与单调栈结合的方式,实现了高效求解。适用于算法面试准备及编程挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目一:Largest Rectangle in Histogram 

参考博客

int largestRectangleArea(vector<int> &height){
	height.push_back(0);//加入一个最小高度,用于清空最后栈中的所有数据
	int length = height.size(),i = 0,maxArea = 0;
	stack<int> stackIndex;
	while(i < length)
	{
		if(stackIndex.empty() || height[i] >= height[stackIndex.top()])stackIndex.push(i++);//高度比前面的大,则进栈
		else
		{
			int index = stackIndex.top();//弹出栈顶元素,并计算高度
			stackIndex.pop();
			int area = height[index] * (stackIndex.empty() ? i : (i - stackIndex.top() - 1));
			maxArea = max(maxArea,area);
		}
	}
	return maxArea;
}


题目二:Maximal Rectangle

 

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

参考博客

int largestRectangleArea(vector<int> &height){
	height.push_back(0);
	int length = height.size(),i = 0,maxArea = 0;
	stack<int> stackIndex;
	while(i < length)
	{
		if(stackIndex.empty() || height[i] >= height[stackIndex.top()])stackIndex.push(i++);
		else
		{
			int index = stackIndex.top();
			stackIndex.pop();
			int area = height[index] * (stackIndex.empty() ? i : (i - stackIndex.top() - 1));
			maxArea = max(maxArea,area);
		}
	}
	return maxArea;
}
int maximalRectangle(vector<vector<char> > &matrix) {
	int row = matrix.size();
	int col = matrix[0].size();
	int i,j;
	vector<vector<int> >dp(row);//dp[i][j]表示从第i个元素开始,包括第i个元素,向上数,直到遇到0时,1的个数,参考该博客
	for(i = 0;i < row;i++)
	{
		vector<int> tmp(col);
		dp[i] = tmp;
	}
	for(j = 0;j < col;j++)dp[0][j] = matrix[0][j] - '0';
	for(i = 1;i < row;i++)
	{
		for(j=0;j < col;j++)
		{
			if(matrix[i][j] == '0')dp[i][j] = 0;
			else dp[i][j] = dp[i-1][j] + 1;
		}
	}
	int maxArea = 0;
	for(i = 0;i < row;i++)
	{
		maxArea = max(maxArea,largestRectangleArea(dp[i]));
	}
	return maxArea;
}


由于参考的博客写的非常好,自己就不想多写了,记录下来供自己以后回顾,希望

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值