Generate Parentheses

Jin Shang bio photo By Jin Shang

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

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Solution:

backtrack

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        backtrack(ans, "", 0,0,n);
        return ans;
    }
    
    void backtrack(vector<string> &ans, string s, int l, int r, int m){
        if(s.size() == 2*m){
            ans.push_back(s);
            return;
        }
        if(l < m){
            backtrack(ans, s+'(', l+1, r, m);
        }
        if(r < l){
            backtrack(ans, s+')',l, r+1, m);
        }
        
    }
};