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 height = [2,1,5,6,2,3]
,
return 10
.
题目解析:
方案一:
这道题目想到了动态规划,m[i,j] = min( m[i,j-1]/(j-i) , height[j] ) * (j-i+1);设置动态设置二维数组,也是以len为主循环。最后遍历整个二维数组,找出最大值。方法正确,但提交的时候,内存超限。还是数组太大造成的。
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int n = height.size();
int **arr = new int*[n];
for(int i = 0;i < n;i++)
arr[i] = new int[n];
for(int i = 0;i < n;i++)
arr[i][i] = height[i];
for(int len = 2;len <= n;len++){
for(int i = 0;i < n-len+1;i++){
int j = i + len -1;
int min = arr[i][j-1]/(j-i) > height[j] ? height[j] : arr[i][j-1]/(j-i);
arr[i][j] = min * (j-i+1);
}
}
int largest = 0;
for(int i = 0;i < n;i++)
for(int j = i;j < n;j++){
if(largest < arr[i][j]){
largest = arr[i][j];
}
}
for(int i = 0;i < n;i++)
delete[] arr[i];
delete[] arr;
return largest;
}
};
方案二:
链接中用到栈的方法,各种各样,回头有时间了再深究……
http://www.cnblogs.com/remlostime/archive/2012/11/25/2787359.html
http://blog.sina.com.cn/s/blog_727d57100100o3e6.html
http://www.2cto.com/kf/201207/140484.html
http://blog.csdn.net/doc_sgl/article/details/11805519
http://www.cnblogs.com/avril/archive/2013/08/24/3278873.html