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:
    void visit(int n, int sum, int k, string str, vector<string> &result)
    {
        if (k == n && sum == 0)
        {
            result.push_back(str);
            return;
        }

        if (k < n)
        {
            k++;
            sum += 1;
            visit(n, sum, k, str+'(', result);
            k--;
            sum -= 1;
        }

        if (sum > 0)
        {
            sum -= 1;
            visit(n, sum, k, str+')', result);
        }
    }
    
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string str;
        visit(n, 0, 0, str, result);

        return result;
    }
};


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