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],但是现在不是求个数,而是要将所有合法的括号排列打印出来。
对一个长度为
2n
的合法排列,第
1
到
代码如下:
class Solution {
private:
void generate(int LP,int RP,string s,vector<string> &result) {
if(LP == 0 && RP == 0) {
// LP 和 RP 均为零,则说明我们已经完成一个合法排列
result.push_back(s);
}
if(LP > 0) {
// LP > 0,可以打印左括号
generate(LP - 1, RP, s + '(', result);
}
if(RP > 0 && LP < RP) {
// LP < RP,可以打印右括号
generate(LP, RP - 1, s + ')', result);
}
}
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
generate(n, n, "", result);
return result;
}
};
思路二:
class Solution {
public:
vector<string> generateParenthesis (int n) {
if (n == 0) return vector<string>(1, "");
if (n == 1) return vector<string> (1, "()");
vector<string> result;
for (int i = 0; i < n; ++i)
for (auto inner : generateParenthesis (i))
for (auto outer : generateParenthesis (n - 1 - i))
result.push_back ("(" + inner + ")" + outer);
return result;
}
};