<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:
    vector<string> generateParenthesis(int n) {
        vector<string> results;

        int numBits = n*2;

        int maxNumStrings = pow(2,numBits);

        //Generate every possible matching string, by thinking of the opening and closing brackets as 1s and 0s.
        //1s are openers. 2s are closers. So if x is 10101010, then the string would be ()()()()
        for (int x = 0; x < maxNumStrings; x++)
        {
            string result = "";
            int numOpeningBrackets = 0;
            for (int i = numBits - 1; i >= 0; i--)
            {
                if (x & (1 << i))
                {
                    result += '(';
                    numOpeningBrackets++;
                }
                else
                {
                    result += ')';
                    numOpeningBrackets--;
                }

                if (numOpeningBrackets < 0) // tried to close a bracket we never opened
                {
                    break;
                }
            }
            if (numOpeningBrackets == 0)
            {
                results.push_back(result);
            }

        }
        return results;
    }
};
10274