题目描述
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution:
题目大意:
实现代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string tmp(n+n,0);
generate(res,n,n,tmp,0);
return res;
}
private:
void generate(vector<string>& res,int l,int r,string tmp,int index)
{
if(l==0 && r==0)//左右括号全部用完;
{
res.push_back(tmp);
return;
}
if(l>0) //l表示左括号剩下的个数;必须先放左括号;
{
tmp[index]='(';
generate(res,l-1,r,tmp,index+1);
}
if(r>0 && r>l) //r表示右括号剩下的个数,但是必须大于左括号剩下的个数;
{
tmp[index]=')';
generate(res,l,r-1,tmp,index+1);
}
}
};