public:
int trap(vector<int>& height) {
//2.分治;找到最高点,并以此划分左右两部分,分别计算左右两部分;
//左部分:递归求得 左部的水量(分)+当前右部即最高点和上级最高点之间的水量(合并)
//右部分:递归求得 右部的水量(分)+当前左部即最高点和上级最高点之间的水量(合并)
int maxHeightPos=0;
vector<int> leftHeight;
vector<int> rightHeight;
for (int i = 1; i < height.size(); i++)
{
if(height[i]>height[maxHeightPos]){
maxHeightPos = i;
}
}
return trapLeft(height,maxHeightPos)+trapRight(height,maxHeightPos);
}
int trapLeft(vector<int> &height,int right){
if(right==0){
return 0;
}
int waterVolumn=0;
int maxHeightPos=0;
for (int i = 1; i < right; i++)
{
if(height[i]>height[maxHeightPos]){
maxHeightPos = i;
}
}
for(int i = maxHeightPos;i <= right;i++){
if(height[i]<height[maxHeightPos]){
waterVolumn+=height[maxHeightPos] - height[i];
}
}
return trapLeft(height,maxHeightPos)+waterVolumn;
}
int trapRight(vector<int> &height,int left){
if(left==height.size()-1){
return 0;
}
int waterVolumn=0;
int maxHeightPos=height.size()-1;
for (int i = height.size()-2; i > left; i--)
{
if(height[i]>height[maxHeightPos]){
maxHeightPos = i;
}
}
for(int i = maxHeightPos;i >= left;i--){
if(height[i]<height[maxHeightPos]){
waterVolumn+=height[maxHeightPos] - height[i];
}
}
return trapRight(height,maxHeightPos)+waterVolumn;
}