85. 最大矩形/C++

在这里插入图片描述

class Solution {
public:
	//leetcode84
    int largestRectangleArea(vector<int> heights) {
	     heights.push_back(0);
	     stack<int> stk;
	     int maxArea = 0;
	     for(int i = 0;i<heights.size();i++)
	     {
	         while(!stk.empty() && heights[i]<heights[stk.top()])
	         {
	             int top= stk.top();
	             stk.pop();
	             maxArea = max(maxArea,heights[top]*(stk.empty()? i:(i - stk.top() -1)));
	         }
	         stk.push(i);
	     }
	     return maxArea;
    }
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty()) return 0;
        int maxArea = 0;
        vector<int> dp(matrix[0].size());
        
        for(int i=0;i<matrix.size();++i){
            for(int j=0;j<matrix[0].size();++j){
                dp[j]= matrix[i][j] == '1' ? dp[j] + 1 : 0;
            }
            maxArea = max(maxArea,largestRectangleArea(dp));
        }
        return maxArea;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 C++ 实现的基于矩形面积的内接最大矩形算法: ```c++ #include<bits/stdc++.h> using namespace std; // 定义一个矩形结构体 struct Rectangle { int width; int height; }; // 计算矩形面积 int area(Rectangle r) { return r.width * r.height; } // 计算内接最大矩形 Rectangle maxInner(Rectangle r) { // 如果矩形的宽或高为1,则返回该矩形 if (r.width == 1 || r.height == 1) { return r; } // 如果矩形的宽和高相等,则返回该矩形 if (r.width == r.height) { return r; } // 如果矩形的宽大于高,则将其分成两个矩形 if (r.width > r.height) { int new_width = r.width / 2; Rectangle left_rect = {new_width, r.height}; Rectangle right_rect = {r.width - new_width, r.height}; // 分别计算左右两个矩形内接最大矩形 Rectangle left_inner = maxInner(left_rect); Rectangle right_inner = maxInner(right_rect); // 返回面积较大的内接最大矩形 return area(left_inner) > area(right_inner) ? left_inner : right_inner; } // 如果矩形的高大于宽,则将其分成两个矩形 else { int new_height = r.height / 2; Rectangle top_rect = {r.width, new_height}; Rectangle bottom_rect = {r.width, r.height - new_height}; // 分别计算上下两个矩形内接最大矩形 Rectangle top_inner = maxInner(top_rect); Rectangle bottom_inner = maxInner(bottom_rect); // 返回面积较大的内接最大矩形 return area(top_inner) > area(bottom_inner) ? top_inner : bottom_inner; } } int main() { // 定义一个矩形 Rectangle r = {10, 6}; // 计算内接最大矩形 Rectangle inner_rect = maxInner(r); // 输出内接最大矩形的宽和高 cout << "Width: " << inner_rect.width << endl; cout << "Height: " << inner_rect.height << endl; return 0; } ``` 以上代码中,我们首先定义了一个矩形结构体,包含矩形的宽和高。然后,我们定义了一个计算矩形面积的函数 `area`。接着,我们实现了计算内接最大矩形的函数 `maxInner`,该函数基于分治思想,将矩形递归地分成两个子矩形,分别计算子矩形内接最大矩形,并返回面积较大的那个矩形。最后,在 `main` 函数中,我们定义了一个矩形,计算其内接最大矩形,并输出其宽和高。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值