<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> ["()"]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>

class Solution {
public:
    bool validParenthesis(string output) {
        int balance = 0;
        for (char c : output) {
            if (c == '(') {
                balance++;
            } else if (c == ')') {
                balance--;
            }
            if (balance < 0) {
                return false;
            }
        }
        return balance == 0;
    }

    void solve(vector<string>& ans, int m, string output, int a, int b) {
        // Base case
        if (m == 0) {
            if (validParenthesis(output)) {
                ans.push_back(output);
            }
            return;
        }

        // Put "(" if possible
        if (a > 0) {
            output += "(";
            solve(ans, m - 1, output, a - 1, b);
            output.pop_back(); // backtrack
        }

        // Put ")" if possible
        if (b > 0) {
            output += ")";
            solve(ans, m - 1, output, a, b - 1);
            output.pop_back(); // backtrack
        }
    }

    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        if (n == 0) return ans;
        solve(ans, 2 * n - 1, "(", n - 1, n);
        return ans;
    }
};

23031