Description:
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:
Example:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Link:
https://leetcode.com/problems/generate-parentheses/#/description
解题方法:
使两个int:left
和right
各表示(
和)
还剩下多少个,用递归生成字符串,过程中需遵守的规则是left 不能大于 right
。并且left
和right
都要大于0。
Tips:
字符串可以直接用运算符'+'
helper(builder + '(', left-1, right);
helper(builder + ')', left, right-1);
Time Complexity:
O(N^2)
完整代码:
vector<string> result;
vector<string> generateParenthesis(int n)
{
int left = n, right = n;
helper("", left, right);
return result;
}
void helper(string builder, int left, int right)
{
if(left > right || left < 0 || right < 0)
return;
if(left == 0 && right == 0)
{
result.push_back(builder);
return;
}
helper(builder + '(', left-1, right);
helper(builder + ')', left, right-1);
}