<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 valid(string s) {
    int balance = 0;  // Balance counter for open and close parentheses
    for (char c : s) {
        if (c == '(') {
            balance++;  // Increase balance for every open parenthesis
        } else {
            balance--;  // Decrease balance for every close parenthesis
        }
        if (balance < 0) {
            return false;  // If balance becomes negative, it's invalid
        }
    }
    return balance == 0;  // In the end, balance should be 0 for valid parentheses
}
    void find(int n,vector<string> &ans,int l,int r,string a)
    {
        if(l==n&&r==n)
        {
            if(valid(a))
            ans.push_back(a);
            return ;
        }
       else{
        if(l<n)
        {
           
            find(n,ans,l+1,r,a+'(');
        }
         if(r<n)
        {
           
            find(n,ans,l,r+1,a+')');
        }
       }

    }
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        string a;
        int l,r;
        find(n,ans,0,0,a);
        return ans;
    }
};
26069