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:
"((()))", "(()())", "(())()", "()(())", "()()()"
关于这道题目,因为和括号有关,开始想用stack,但是应该用回溯法。(个人感觉列举所有情况的题目都可以用回溯法得到)。因为这道题目中涉及到了左右括号,两个元素,所以回溯子函数中需要两个参数指明左右括号的两个情况。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> re;
string s;
sub(re,s,n,n);
return re;
}
void sub(vector<string> &result,string &aresult,int left,int right){
if(right<left) return;
if(left==0&&right==0) result.push_back(aresult);
if(left>=1){
aresult.push_back('(');
sub(result,aresult,left-1,right);
aresult.pop_back();
}
if(right>=1){
aresult.push_back(')');
sub(result,aresult,left,right-1);
aresult.pop_back();
}
}
};