22. 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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

AC代码

void digui(vector& ans, string str, int n, int numl, int numr) {
    if (numl == n && numr == n) {
        ans.push_back(str);
        return;
    }
    if (numl < n) digui(ans, str + '(', n, numl + 1, numr);
    if (numr < n && numr < numl) digui(ans, str + ')', n, numl, numr + 1);
}

class Solution {
public:
    vector generateParenthesis(int n) {
        vector ans;
        string str;
        digui(ans, str, n, 0, 0);
        return ans;
    }
};

总结

你可能感兴趣的:(22. Generate Parentheses/括号生成)