22. Generate Parentheses

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
8
> [
> "((()))",
> "(()())",
> "(())()",
> "()(())",
> "()()()"
> ]
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//
// Created by chaopengz on 2017/10/10.
//

#include "head.h"
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
add(res,"",n,0);
return res;
}
void add(vector<string> &v,string s,int l,int r)
{
if (!l && !r)
{
v.push_back(s);
return;
}
//加入左括号
if(l) add(v,s+"(",l-1,r+1);
//加入右括号
if(r) add(v,s+")",l,r-1);
}
};