<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 check(string& s){
        stack<char> st;
        for(auto it : s){
            if(it=='(') st.push(it);
            else{
                if(st.size()==0) return false;
                char a = st.top(); st.pop();
                if(it==')' && a!='(') return false;
            }
        }
        return st.empty();
    }

    void GP(vector<string>& ans, string temp, int open, int close, int n){
        if(temp.size()==2*n){
            if(check(temp)){
                ans.push_back(temp);
            }
            return;
        }
        if(open<n){
            GP(ans, temp+"(", open+1, close, n);
        }
        if(close<open){
            GP(ans, temp+")", open, close+1, n);
        }
    }

    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        GP(ans, "", 0, 0, n);
        return ans;
    }
};
18475