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;
dfs(res, "", 2 * n, 0, 0);
return res;
}
private:
void dfs(vector<string>& res, string tmp, int ind, int sum, int start) {
if (sum < 0) {
return;
}
if (start == ind) {
if (sum == 0) {
res.push_back(tmp);
}
return;
}
dfs(res, tmp + "(", ind, sum + 1, start + 1);
dfs(res, tmp + ")", ind, sum - 1, start + 1);
}
};
注意递归的时候,满足条件也要return。