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

#include <bitset>

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        int len = n * 2;
        vector<string> answer;
        
        for(int bit = 0; bit < (1<<(len - 1)); bit++){
            int x = 0;
            for(int i = 0; i < len - 1; i++){;
                if(bit&(1<<i)) x++;
            }
            if(x == n){
                bitset<16> bs(bit);
                string b = bs.to_string();
                if(n < 8) {b = b.substr(16 - len);}
                b[0] = '(';
                int judge = 1;
                int pos = 1;
                while(judge >= 0 && pos < len){
                    if(b[pos] == '0'){
                        judge++;
                        b[pos] = '(';
                    }
                    if(b[pos] == '1'){
                        judge--;
                        b[pos] = ')';
                    }
                    pos++;
                }
                if(judge == 0) answer.push_back(b);
            }
        }
    return answer;
    }
};
9970