题目:
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> result;
vector<string> generateParenthesis(int n) {
string tmp;
generate(tmp, n, n);
return result;
}
void generate(string &res, int m, int n){
if(m == 0 && n == 0){
result.push_back(res);
return;
}
if(m > 0){
res.push_back('(');
generate(res, m - 1, n);
res.pop_back();
}
if(n > 0 && m < n){
res.push_back(')');
generate(res, m, n - 1);
res.pop_back();
}
}
};