今天第一天开始刷Leetcode,一不小心抽到了一道hard,搞了一下午也没搞出来,半夜突然有了灵感,想用递归试一试,结果调了调居然AC了,效率还高于94.01%·······
先把代码贴在下面了,图解什么的······该休息了,改天吧
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if ((heights.size() == 0))
return 0; //判断输入不为空
vector<int>::iterator it = heights.begin(), it_end=heights.end();
int max = 0, remain=0;
while (it != heights.end())
//跳出递归的两种条件:it迭代至end、当前项小于最底层递归的高度标记
//第二种情况需要将上次递归中返回的count作为rest带入下一次递归
remain = recursion_84(it, it_end, max, remain );
return max;
}
int recursion_84(vector<int>::iterator &it, vector<int>::iterator &it_end, int &max, int past)
{
int count = past, height = *it, remain=0, temp=0;//进入函数时it为第一项,本层递归的识别标志为height
while (height!=0)//主循环
{
while ((it != it_end) && (height == *it))//将与该层标志相等的项目累加至count
count++, it++, remain=0;
if ((it == it_end)||(height > *it))//迭代至尾部,或下一层低于本层标记时->判断是否为max,并结束本层递归
{
if (max < count*height)
max = count*height;
return count;
}
else//下一项高于本层标记,进入下一层递归
{
//下层递归结束后返回下层递归的count累加至本层count之上
//将past存入remain,然后继续主循环
temp = recursion_84(it, it_end, max, remain);
count +=temp-remain;
remain = temp;
}
}
it++;
return 0;
}
};