<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:
    // Function to generate a string from the current stack
    string getString(stack<char>& st) {
        string s = "";
        stack<char> temp = st;  // Copy the original stack
        
        // Reverse order of the stack to generate the correct string
        vector<char> tempStorage;
        while (!temp.empty()) {
            tempStorage.push_back(temp.top());
            temp.pop();
        }
        int n=tempStorage.size();
        for (char ch : tempStorage) {
            s += ch;
        }
        reverse(s.begin(), s.end());
        return s;
    }

    // Backtracking function to generate parentheses
    void backtrack(int n, int m, vector<string>& v, stack<char>& s, int k) {
        if (n == k && m == k) {  // Condition to check if we've reached the limit
            string validCombo = getString(s);
            v.push_back(validCombo);
            return;
        }
        
        // If we can add an opening parenthesis
        if (n < k) {
            s.push('(');
            backtrack(n + 1, m, v, s, k);
            s.pop();  // Backtrack by popping
        }
        
        // If we can add a closing parenthesis
        if (m < n) {
            s.push(')');
            backtrack(n, m + 1, v, s, k);
            s.pop();  // Backtrack by popping
        }
    }

    // Main function to generate parentheses
    vector<string> generateParenthesis(int n) {
        stack<char> st;
        vector<string> v;
        backtrack(0, 0, v, st, n);  // Start the backtracking with initial values
        return v;
    }
};

22120