classSolution{public:inttrap(vector<int>& height){int sum =0;for(int i =0; i < height.size(); i++){int rHeight = height[i];// 记录右边柱子的最高高度int lHeight = height[i];// 记录左边柱子的最高高度for(int r = i +1; r < height.size(); r++){if(height[r]> rHeight) rHeight = height[r];}for(int l = i -1; l >=0; l--){if(height[l]> lHeight) lHeight = height[l];}int h =min(lHeight, rHeight)- height[i];if(h >0) sum += h;}return sum;}};
单调栈
classSolution{public:inttrap(vector<int>& height){int result =0;
stack<int> stk;
stk.push(0);for(int i =1;i<height.size();i++){while(!stk.empty()&& height[i]> height[stk.top()]){int mid = stk.top();
stk.pop();if(!stk.empty()){int h =min(height[stk.top()],height[i])- height[mid];int w = i - stk.top()-1;
result += h*w;}}
stk.push(i);}return result;}};