22. Generate 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<string> generateParenthesis(int n) {
string s="";
helper(n,n,s);
return ans;
}
};
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.