1.题目
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
2.思路
找到所有符合规则的括号排序方法。那么,左右括号的出现有什么规则呢?
1. 最后左右括号肯定是相等的,并且等于n
2. 从左向右数,右括号出现的次数一定不能比左括号多(如果多了代表表达式有误)
由此,可以使用递归,代码如下:
class Solution {
public:
// left 和 right 分别代表了当前出现的左右括号的数目
vector<string> ans;
void helper(int left,int right,int n,string ret)
{
if(left == n && right == n)
ans.push_back(ret);
if(left != n)
helper(left+1,right,n,ret+"(");
if(left > right && right != n)
helper(left,right+1,n,ret+")");
}
vector<string> generateParenthesis(int n)
{
helper(0,0,n,"");
return ans;
}
};