<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<char> pathenChars{'(', ')'};

    vector<string> generatePathens(int n, 
        string &buildingPathen, int index = 0) {
        vector<string> results;
        for (int i = 0; i < pathenChars.size(); i++){
            buildingPathen[index] = pathenChars[i];
            if (index == n-1 ){
                if (isValidPathen(buildingPathen)) results.push_back(buildingPathen);
            } else {
                vector<string> otherResults = generatePathens(n, buildingPathen, index + 1);
                results.insert(results.end(), otherResults.begin(), otherResults.end());
            }
        }
        return results;
    }

    bool isValidPathen(string pathen){
        int len = pathen.size(), count = 0;
        for (int i = 0; i < len; i++){
            if (pathen[i] == '(') {
                count++;
                int remainingChars = len - i - 1;
                if (count > remainingChars){
                    return false;
                }
            } else if (count > 0) {
                count--;
            } else {
                return false;
            }
        }
        return count == 0;
    }

    vector<string> generateParenthesis(int n) {
        string pathen = "";
        for (int i = 0; i < n*2; i++){
            pathen += ' ';
        }
        return generatePathens(n*2, pathen);
        /*
        n = 1
        ()
        n = 2
        ()()
        (())
        n = 3
        (()))        
        */   
    }
};
18171