法一:
class Solution {
public :
char p[2 ] = {'(' , ')' };
int half;
void Generate_Parentheses(vector <string > &rel, int stt, int left, int right, int n, string tmp) {
if (stt == n) {
if (left == half)
rel.push_back(tmp);
return ;
}
for (int i = 0 ; i < 2 ; i++) {
tmp += p[i];
if ((left + 1 >= right + 2 *i) && (left + 1 - i <= half))
Generate_Parentheses(rel, stt + 1 , left + 1 - i, right + i, n, tmp);
tmp.pop_back();
}
}
vector <string > generateParenthesis(int n) {
vector <string > rel;
string tmp;
half = n;
Generate_Parentheses(rel, 0 , 0 , 0 , n << 1 , tmp);
return rel;
}
};
法二:
class Solution {
public :
vector <string > generateParenthesis(int n) {
vector <string > res;
string sol;
genParen(sol, 0 , 0 , n, res);
return res;
}
private :
void genParen(string & sol, int open, int close, int total, vector <string > & res) {
if (open == total && close == total) {
res.push_back(sol);
return ;
}
if (open < total) {
sol += '(' ;
genParen(sol, open + 1 , close, total, res);
sol.resize(sol.length() - 1 );
}
if (close < open) {
sol += ')' ;
genParen(sol, open, close + 1 , total, res);
sol.resize(sol.length() - 1 );
}
}
};