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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:递归
代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string temp;
if(n>0) generate(res,temp,n,n);
return res;
}
void generate(vector<string> &res, string temp,int m, int n){
if(m==0 && n==0){
res.push_back(temp);
}
else{
if(m!=0) generate(res,temp+"(",m-1,n);
if(m<n && n!=0) generate(res,temp+")",m,n-1);
}
}
};