22. 括号生成

  1. 题目链接

  2. 解题思路:从左往右生成,生成的过程中,保证右括号不能比左括号多。

  3. 代码

    class Solution {
    public:
    
        // 总共有n个括号对,left_res就是左括号还能使用的数目,right_res就是右括号还能使用的数目
        // 要保证左括号大于等于右括号数目,即left_res <= right_res
        void process(vector<string> &ans, string &path, int left_res, int right_res) {
            if (left_res == 0 && right_res == 0) {
                ans.push_back(path);
                return;
            }
            // 加左括号还是右括号
            if (left_res > 0) {    // 只要左括号有  就可以加
                path.push_back('(');
                process(ans, path, left_res - 1, right_res);
                path.pop_back();    // 恢复现场
            }
            if (right_res > left_res) {    // 生成的过程中,时刻保证    right_res >= left_res
                path.push_back(')');
                process(ans, path, left_res, right_res - 1);
                path.pop_back();    // 恢复现场
            }
        }
    
    
        vector<string> generateParenthesis(int n) {
            vector<string> ans;
            string path = "";
            process(ans, path, n, n);
            return ans;
        }
    };
    
posted @ 2024-12-18 10:59  ouyangxx  阅读(13)  评论(0)    收藏  举报