42. Trapping Rain Water 暴力解法

class Solution {
public:
    int trap_recursion(vector height, int left, int right){
        if(left == right) return 0;
        int max_left = left, pos_left = left;
        int max_right = right, pos_right = right;
        int max_trap = 0;
        while(pos_right > pos_left) {
            if(height[pos_left] >= height[max_left]) max_left = pos_left;
            if(height[pos_right] >= height[max_right]) max_right = pos_right;
            if(height[max_left] > height[max_right]) pos_right--;
            else pos_left++;
        }
        for(int i = max_left + 1; i < max_right; i++)
            max_trap = max_trap + (min(height[max_left], height[max_right]) - height[i]);
        return max_trap + trap_recursion(height, left, max_left) + trap_recursion(height, max_right, right);
    }
    
    int trap(vector& height) {
        //brute force
        return trap_recursion(height, 0, height.size()-1);
    }
};

1.首先找出最高的两个点max_left、max_right,计算面积max_trap
2.递归计算max_left左侧的部分以及max_right右侧的部分,与max_trap相加返回结果

你可能感兴趣的:(leetcode,c++,OJ随笔)