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

        int size = 2 * n - 1;
        vector<bool> pars;
        pars.resize(size, false);

        int count = 0;
        int i = 0;
        while (true)
        {
            while (count < n)
            {
                pars[i++] = true;
                count++;
            }

            string temp;
            temp.resize(size + 1);
            for (int j = 0; j < size; j++)
                temp[j] = pars[j] ? '(' : ')';
            temp[size] = ')';
            res.push_back(temp);

            while (i == 2 * count - 1)
            {
                pars[--i] = false;
                count--;

                if (count == 0) break;

                i--;
                while (pars[--i] == false);
                i++;
            }

            if (count == 0) break;

            pars[i-1] = false;
            count--;
        }

        return res;
    }
};
8755