题目:
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;
if(n <= 0) return res;
string oneCombination;
generateParenthesisCore(n, 0, 0, oneCombination, res);
return res;
}
private:
void generateParenthesisCore(int n, int left, int right, string oneCombination, vector<string> &res){
if(left < right) return;//非法,直接返回
if(left == n && right == n){//完成一个组合
res.push_back(oneCombination);
return;
}
if(left != n){
oneCombination.push_back('(');
generateParenthesisCore(n, left+1, right, oneCombination, res);
oneCombination.erase(oneCombination.size()-1);//删除string最后一个字符
}
if(right != n){
oneCombination.push_back(')');
generateParenthesisCore(n, left, right+1, oneCombination, res);
oneCombination.erase(oneCombination.size()-1);//这句可以没有
}
}
};