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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
solution:
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
solution:
class Solution {
public:
void deep(vector<string> & ans, int n, int step, int use, string str) {
if (step == 2*n) {
if (use == 0) ans.push_back(str);
return;
}
if (use > 0) deep(ans, n, step+1, use-1, str+')');
if (use < n) deep(ans, n, step+1, use+1, str+'(');
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
deep(ans, n, 0, 0, "");
return ans;
}
};