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;
scan(0, 0, "", n, res);
return res;
}
void scan(int l, int r, string path, int &n, vector<string> &res){
if (r == n){
res.push_back(path);
return;
}
if (l<n)
scan(l + 1, r, path+'(', n, res);//这条分支执行完后就会进入下一个if,而且每个分支一定能有结果
if (r<l)
scan(l, r + 1, path+')' , n, res);
}
};