vector<string> generateParenthesis(int n) {
vector<string> ans;
string s;
if (n>0) generator(ans, s, 0, 0, n);
return ans;
}
// l/r: number of '(' / ')'
void generator(vector<string> & ans, string s, int l, int r, int n) {
if (l == n) {
ans.push_back(s+string().assign(n-r, ')'));
return;
}
generator(ans, s+'(', l+1, r, n);
if (l>r) generator(ans, s+")", l, r+1, n);
}
- void genPar(vector<char> &vt,int sum, int beg, int end, int acc) {
- //第0位置肯定放(,那么和这个左括号匹配的右括号可能的位置是2*i+1,然后按照此类方法再去处理括号里面的元素和括号外面的元素
- vt[beg] = '(';
- ++acc;
- if (beg + 1 == end && acc +1 == sum){
- vt[end] = ')';
- for (int j=0; j< sum; ++j)
- cout<<vt[j];
- cout<<endl;
- return;
- }
- for(int i = beg + 1; i<= end; i +=2 ) {
- int tmp = acc;
- vt[i] = ')';
- if (i - beg >=3)
- genPar(vt,sum,beg+1, i - 1,acc + 1);
- if (end - i >=2)
- genPar(vt, sum, i+1,end,acc + i -beg );
- }
- }
-
- int main() {
- int n =3;
- vector<char> vt(2*n);
- int acc = 0;
- genPar(vt,2*n,0,2*n - 1,acc);
- /*vector<char> vt(6);
- par(3,3,vt,0);*/
- }