<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>

// brute force
// Time O(2^(2n) * n) We are generating all possible strings of length 2n. At each character, we have two choices: choosing ( or ), which means there are a total of 2^2n
// unique strings.
// Space O(2^(2n) * n)
class Solution {

public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        queue<string> q;
        q.push("");
        while (!q.empty()) {
            string cur = q.front();
            q.pop();
            if (cur.length() == 2 * n) {
                if (isValid(cur)) {
                    res.push_back(cur);
                }
                continue;
            }
            q.push(cur + ")");
            q.push(cur + "(");
        }
        return res;
    }
private:
    bool isValid(string pString) {
        int leftCount = 0;
        for (char p : pString) {
            if (p == '(') {
                leftCount++;
            } else {
                leftCount--;
            }
            if (leftCount < 0) {
                return false;
            }
        }
        return leftCount == 0;
    }
};

// Backtracking, Keep Candidate Valid
class Solution1 {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        helper(n, 0, 0, res, "");
        return res;
    }
    
    void helper(int n, int left, int right, vector<string>& res, string out){
        if(left == n && right == n) {
            res.push_back(out);
            //return;
        }
        
        if(right > left || right > n || left > n) return;
        
        helper(n, left+1, right, res, out+'(');
        helper(n, left, right+1, res, out+')');
    }
};
30929