求最大的矩形面积

84. Largest Rectangle in Histogram

第一次想的时候,想到了动态规划,但是还有一个复杂度更低的方法,就是采用栈的方式。第二种方法是看了厉害的人的博客之后才理解的。它的思想就是从后往前遍历,使用栈保存当前遍历到的最小值,这个值是不断更改的,同时,没遍历一次,计算一次当前的面积。

在做leetcode的时候发现,从后往前遍历的题目有很多,巧妙的使用栈的结构的方法也有很多,这就需要自己慢慢的在做题的过程中,慢慢的理解掌握了。

代码比较丑陋,还望大家多提建议。

 1 //动态规划,但是超时了
 2  int largestRectangleArea(vector<int>& heights) {
 3         if(heights.size()==0)   return 0;
 4         vector<vector<int>>result;
 5         vector<int>temp;
 6         int i,j;
 7         int minValue=heights[0],maxValue=heights[0];
 8         temp.push_back(heights[0]);
 9         for(i=1;i<heights.size();i++){
10             if(heights[i]<minValue)
11                 minValue=heights[i];
12             maxValue=temp[i-1]>(minValue*(i+1))?temp[i-1]:minValue*(i+1);
13             temp.push_back(maxValue);
14         }
15         result.push_back(temp);
16         for(i=1;i<heights.size();i++){
17             vector<int>temp(heights.size(),0);
18             int minValue=heights[i];
19             // temp[i]=heights[i];
20             for(j=i;j<heights.size();j++){
21                 if(heights[j]<minValue)
22                     minValue=heights[j];
23                 maxValue=temp[j-1]>(minValue*(j-i+1))?temp[j-1]:minValue*(j-i+1);
24                 maxValue=maxValue>result[i-1][j]?maxValue:result[i-1][j];
25                 temp[j]=maxValue;
26             }
27             result.push_back(temp);
28         }
29         return result[heights.size()-1][heights.size()-1];
30     }
 1 //使用栈的方法    
 2 int largestRectangleArea(vector<int>& heights) {
 3         if(heights.size()==0)   return 0;
 4         int result=0,count=1,topValue;
 5         stack<int>st;
 6         st.push(heights[0]);
 7         for(int i=1;i<heights.size();i++){
 8             topValue=st.top();
 9             if(heights[i]>=topValue)
10                 st.push(heights[i]);
11             else{
12                 count=1;
13                 while(!st.empty()&&st.top()>heights[i]){//直接用st.top(),代码会更简洁
14                     result=max(result,st.top()*count);
15                     // result=result>topValue*count?result:topValue*count;
16                     count++;
17                     st.pop();
18                 }
19                 while(count-->0){//在循环条件内自减使代码简洁
20                     st.push(heights[i]);
21                 }
22             }
23         }
24         count=1;
25         while(!st.empty()){
26             // topValue=st.top();
27             // result=result>topValue*count?result:topValue*count;
28             result=max(result,st.top()*count);
29             count+=1;
30             st.pop();
31         }
32         return result;
33     }

 

posted @ 2016-09-12 21:35  胖子到瘦子  阅读(690)  评论(0编辑  收藏  举报