相关问题
Discription
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。
约束条件:任何时候,左括号个数必须大于或等于右括号个数。
时间复杂度:
?
空间复杂度:
代码
class Solution {
public:
// left: 左括号个数
// right: 右括号个数
void add(vector<string> &res, string cur, int left, int right, int n)
{
// 边界条件
if (right == n)
{
res.push_back(cur);
return;
}
if (left == right) // 确保 left >= right
add(res, cur + "(", left + 1, right, n);
else if (left < n)
{
add(res, cur + "(", left + 1, right, n);
add(res, cur + ")", left, right + 1, n);
}
else
add(res, cur + ")", left, right + 1, n);
}
vector<string> generateParenthesis(int n)
{
vector<string> res;
string cur = "";
add(res, cur, 0, 0, n);
return res;
}
};