# Generate Parentheses -- leetcode

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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

#include <iostream>
#include <vector>
#include <string>
using namespace std;

void createParenthesis(vector<string>&, string, int, int);
vector<string> generateParenthesis(int);
int main()
{
int n;
cin >> n;
vector<string> ans = generateParenthesis(n);
for (int i = 0; i < ans.size(); ++i) {
cout << ans[i] << endl;
}
return 0;
}
/*
left : 左括号剩余个数
right : 右括号剩余个数
*/
void createParenthesis(vector<string>& ans, string s, int left, int right) {
//左右括号剩余为0，保存此序列
if (left == 0 && right == 0)
ans.push_back(s);

//剩余左括号个数大于0，可以继续打印左括号
if (left > 0)
createParenthesis(ans, s + '(', left - 1, right);

//剩余右括号个数大于0，且剩余左括号的个数小于右括号
//即已经打印的左括号个数大于已经打印的右括号的个数，可以继续打印左括号
if (right > 0 && left < right)
createParenthesis(ans, s + ')', left, right - 1);
}

vector<string> generateParenthesis(int n) {
vector<string> ans;
if (n <= 0) return ans;
string s = "";
createParenthesis(ans, s, n, n);
return ans;
}

#### leetcode之 Generate Parentheses

2013-10-26 23:19:18

#### LeetCode 22：Generate Parentheses的递归，回溯两种解法

2015-08-24 11:29:56

#### LeetCode 22 — Generate Parentheses（C++ Java Python）

2014-04-17 11:11:41

#### [leetcode]Generate Parentheses 生成圆括号 python实现

2016-06-12 09:36:27

#### LeetCode 22 Generate Parentheses（生成括号）

2015-11-10 22:41:54

#### leetCode 22.Generate Parentheses (生成括号) 解题思路和方法

2015-07-06 22:11:08

#### LeetCode 22 Generate Parentheses (C,C++,Java,Python)

2015-05-10 21:11:15

#### 【LeetCode】Generate Parentheses 解题报告

2014-10-16 15:26:03

#### LeetCode c语言-Generate Parentheses和买票找零问题

2017-09-18 17:35:23

#### leetcode-java-22. Generate Parentheses

2016-06-09 21:28:09