Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
For example,
Given heights = [2,1,5,6,2,3]
,
return 10
.
解法一:DP
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if(heights.empty()) return 0; //注意单独判断vector为空的情况,不然提交容易报错
int n = heights.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
int i, step, tmp, ans;
for(i = 0; i < n; ++i) {
dp[i][i] = heights[i];
}
//ans = dp[0][0];
for(step = 1; step < n; ++step) {
for(i = 0; i+step < n; ++i) {
tmp = findmin(heights, i, i+step);
dp[i][i+step] = max(dp[i][i+step-1], max(dp[i+1][i+step], tmp*(step+1))); //状态转移方程
//ans = max(ans, dp[i][i+step]);
}
}
return dp[0][n-1]; //返回
}
int findmin(vector<int>& heights, int i, int j) { //找到最低高度h,调用该函数,使时间复杂度较高,最终超时,未能AC
vector<int>::iterator res;
res = min_element(begin(heights)+i, begin(heights)+j+1);
return *res;
}
};
这道题让求直方图中最大的矩形,刚开始看到求极值问题以为要用DP来做,可是想不出递推式,只得作罢。这道题如果用暴力搜索法估计肯定没法通过OJ,但是我也没想出好的优化方法,在网上搜到了网友水中的鱼的博客,发现他想出了一种很好的优化方法,就是遍历数组,每找到一个局部峰值,然后向前遍历所有的值,算出共同的矩形面积,每次对比保留最大值,代码如下:
解法二:
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int res = 0;
for (int i = 0; i < heights.size(); ++i) {
if (i + 1 < heights.size() && heights[i] <= heights[i + 1]) {
continue;
}
int minH = heights[i]; //找出局部最高点
for (int j = i; j >= 0; --j) {
minH = min(minH, heights[j]);
int area = minH * (i - j + 1);
res = max(res, area);
}
}
return res;
}
};
后来又在网上发现一种比较流行的解法,是利用栈来解,可参见网友实验室小纸贴校外版的博客,但是经过仔细研究,其核心思想跟上面那种剪枝的方法有异曲同工之妙,这里维护一个栈,用来保存递增序列,相当于上面那种方法的找局部峰值,当当前值小于栈顶值时,取出栈顶元素,然后计算当前矩形面积,然后再对比当前值和新的栈顶值大小,若还是栈顶值大,则再取出栈顶,算此时共同矩形区域面积,照此类推,可得最大矩形。代码如下:
解法三:
class Solution {
public:
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 cur = s.top();
s.pop();
res = max(res, height[cur] * (s.empty() ? i : (i - s.top() - 1)));
--i;
}
}
return res;
}
};