LeetCode 22. Generate Parentheses
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
I am not too sure what is going wrong with my code below. I am using dfs to generate all combinations of well formed parenthesis and I do this by keeping track of the number of left brackets remaining and the number of right brackets remaining. However, the number of remaining brackets are different after I return from a recursion call which causes there to be extra brackets.
vector<string> generateParentheses(int n) {
vector<string> result;
dfs(result, "", n, n);
return result;
}
void dfs(vector<string> &result, string s, int num_left, int num_right){
if(num_left == 0 && num_right == 0){
result.push_back(s);
}
if(num_left > 0){
dfs(result, s += "(", num_left - 1, num_right);
}
if(num_right > 0 && num_right > num_left){
dfs(result, s += ")", num_left, num_right - 1);
}
}