22. Generate Parentheses

 22Generate Parentheses


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

 

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

 

Constraints:

  • 1 <= n <= 8

Solution in C++


class Solution {
public:vector<string>ans;
    
    void helper(int o,int c,string &s){
        if(o==0 && c==0){
            ans.push_back(s);
            return;
        }
        if(o>0){
            s.push_back('(');
            helper(o-1,c,s);
            s.pop_back();
        }
        if(c>0){
            if(c>o){
               s.push_back(')');
            helper(o,c-1,s);
            s.pop_back();  
            }
           
        }
    }
    vector<stringgenerateParenthesis(int n) {
        string s="";
       helper(n,n,s);
        return ans;
    }
};

Post a Comment

0 Comments