Generate Parentheses

Desicription

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:

1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<string> res;
vector<string> generateParenthesis(int n) {
addPair("", n, 0);
return res;
}
private:
void addPair(string str, int n, int m){
if(!n && !m){
res.push_back(str);
return ;
}
if(m)
addPair(str+')', n, m-1);
if(n)
addPair(str+'(', n-1, m+1);
}
};