[LeeCode]#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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
给定n,列出所有长度为2n的合法括号序列
解题思路:
1、用递归算法,其数据符合重复生成的特点。
2、当左括号个数==右括号个数相等 字符串只添加“(”。
3、当左括号个数 > 右括号个数,
判断左括号个数 ==n,
小于的话多定义一个字符串,一个添加“(”,
另一个添加“)”。
4、当字符串个数 == 2n, 压入容器。
class Solution {
public:
void generate(int n, vector<string>& c, string d, int count_left) {
if (d.size() == 2 * n) {
c.push_back(d);
return;
}
if (count_left == d.size() - count_left) {
d += "(";
generate(n, c, d, count_left+1);
} else {
if (count_left != n) {
string a = d;
a += "(";
generate(n, c, a, count_left+1);
}
d += ")";
generate(n, c, d, count_left);
}
}
vector<string> generateParenthesis(int n) {
int countLeft = 0;
vector<string> a;
string b = "(";
generate(n, a, b, 1);
return a;
}
};