<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 isvalid(vector<char> v){
        stack<char> st;
        for(int i=0;i<v.size();i++){
            if(v[i]=='('){
                st.push('(');
            }else{
                if(st.empty()){
                    return false;
                }
                st.pop();
            }
        }
        if(st.empty()){
            return true;
        }
        return false;
    }
    vector<string> generateParenthesis(int n) {
        vector<char> v;
        for(int i=0; i<n; i++){
            v.push_back('(');
        }
        for(int i=0; i<n; i++){
            v.push_back(')');
        }
        set<vector<char>> s;
        do{
            s.insert(v);
        }while(next_permutation(v.begin(),v.end()));
        vector<string> ans;
        for(auto &i:s){
            if(isvalid(i)){
                string str="";
                for(int j=0; j<i.size(); j++)
                {
                    str.push_back(i[j]);
                }
                ans.push_back(str);
            }
        }
        return ans;
    }
};
29714