1 #include<iostream>
2 #include<vector>
3 #include <algorithm>
4 using namespace std;
5 int looktrap(vector<int>& height,int position,int &add, vector<int> &left, vector<int>& right,int n) {
6 //当n==1 即只有一个数字时或者position == n - 1 说明已经到头 开始读取
7 if (n==1||position == n - 1) {
8 //循环
9 for (int i = 0; i < n; i++) {
10 //比较左边最大和右边最大哪个小
11 int level = min(left[i], right[i]);
12 add += max(0, level - height[i]);
13 }
14 return add;
15 }
16 //找到position位置的左边最大
17 left[position] = max(left[position - 1], height[position - 1]);
18 //找到n- position-1位置的右边最大
19 right[n- position-1] = max(right[n - position], height[n - position]);
20 //递归
21 add=looktrap(height, position+1, add,left,right,n);
22 return add;
23 }
24
25 class Solution {
26 public:
27 int trap(vector<int>& height) {
28 //add一开始为0
29 int add = 0;
30 ////n是height的长度
31 int n = height.size();
32 //存放左边与右边的最大值
33 vector<int> left(n), right(n);
34 //调用递归
35 looktrap(height, 1, add, left, right,n);
36 return add;
37 }
38 };
39
40 int main() {
41 Solution sol;
42 vector<int> height = { 1 };
43 int num=sol.trap(height);
44 cout << num << endl;;
45 }