LeetCode: Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"



class Solution {
public:
    vector<string> generateParenthesis(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int lp = n;
        int rp = n;
        vector<string> res;
        string str = "";
        generate(res, str, lp, rp);
        return res;
    }
    void generate(vector<string> &res, string str, int lp, int rp){
        if(lp == 0 && rp == 0){
            res.push_back(str);
            return;
        }
        string temp = str;
        if(lp > 0){
            temp+="(";
            generate(res, temp, lp -1, rp);
        }
        temp = str;
        if(rp > lp){
            temp += ")";
            generate(res, temp, lp, rp - 1);
        }
        return;
    }
    
};


你可能感兴趣的:(LeetCode: Generate Parentheses)