Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

22. Generate Parentheses 🌟🌟

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Backtracking

class Solution {
private:
    void backtrack(vector<string>& ans, string& s, int open, int close)
    {
        if (open == 0 && close == 0) {
            ans.push_back(s);
            return;
        }
        if (open > 0) {
            s.push_back('(');
            backtrack(ans, s, open - 1, close);
            s.pop_back();
        }
        if (close > open) {
            s.push_back(')');
            backtrack(ans, s, open, close - 1);
            s.pop_back();
        }
    }

public:
    vector<string> generateParenthesis(int n)
    {
        vector<string> ans;
        string s;
        backtrack(ans, s, n, n);
        return ans;
    }
};