leetcode Maximal Rectangle

本文介绍了一个LeetCode上的经典题目“最大矩形”的C++实现方案。该算法利用了栈的数据结构来求解二维矩阵中由'1'构成的最大全为1的矩形面积。文章详细展示了如何通过逐行计算高度并使用辅助函数maximalRectangleHelper来找出最大矩形面积。

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

此题参考


http://www.cnblogs.com/lichen782/p/leetcode_maximal_rectangle.html

虽然和作者的代码大同小异,但是用C++实现提交后一直提示Runtime Error 

贴出不知道问题在哪的自己的代码

class Solution
{

public:
    int maximalRectangle(vector<vector<char> > &matrix)
	{
		int rowNum = matrix.size();
		int colNum = matrix[0].size();

		if(rowNum==0||colNum==0)
			return 0;		

		vector<vector<int> > height(rowNum, vector<int>(colNum+1));	

		int maxArea = 0;

		for(int i = 0; i < rowNum; ++i)
			for(int j = 0; j < colNum; ++j)
			{
				if(matrix[i][j]=='0')
					height[i][j]=0;
				else
				{
					height[i][j] = i==0 ? 1:height[i-1][j]+1; 				
				}			
			}

		for(int i = 0; i < rowNum; ++i)
		{
			int tempArea = maximalRectangleHelper(height[i]);
			if(maxArea<tempArea)
				maxArea = tempArea;
		}

		return maxArea;
        
    }

	int maximalRectangleHelper(vector<int> &height)
	 {
		 stack<int> heightStack;
		 int maxarea = 0;
		 int i = 0;

		 while(i<height.size())
		 {
			 if(heightStack.empty()||height[heightStack.top()]<=height[i])
			{
			    heightStack.push(i);
			    ++i;
			}
			 else
			 {
				 int topIndex = heightStack.top();
				 heightStack.pop();
				 maxarea = max(maxarea, height[topIndex]*(heightStack.empty()?i:i-heightStack.top()-1));
			 
			 }
		 
		 }

		 return maxarea;	 
	 
	 }

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值