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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
given n = 0, a solution set is:
[""]
Mycode:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
if(!n)
{
ans.push_back("");
return ans;
}
backtrack(ans, "", 0, 0, n);
return ans;
}
void backtrack(vector<string>& ans, string cur, int left, int right, int max){
if (cur.length() == max * 2) { //递归函数先定义出口
ans.push_back(cur);
return;
}
//每次递归有两个均等的事情:要么加左括号,要么右括号
if (left < max) //能加左括号,就加左括号
backtrack(ans, cur+"(", left+1, right, max);
if (right < left) //能加右括号,就加右括号
//不可else if(right < left)
backtrack(ans, cur+")", left, right+1, max);
}
};