9.6 Implement an algorithm-to-print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
EXAMPLE
Input:3
Output: (()), (()), (() (), () () () () () () () () () () () () () ()
Leetcode on the original topic, see my previous blog generate parentheses generate parentheses.
Solution One:
classSolution { Public: Vector<string> Generateparens (intN) {Set<string>T; if(n = =0) T.insert (""); Else{vector<string> Pre = Generateparens (N-1); for(Auto a:pre) { for(inti =0; I < a.size (); ++i) {if(A[i] = ='(') {A.insert (A.begin ()+ i +1,'('); A.insert (A.begin ()+ i +2,')'); T.insert (a); A.erase (A.begin ()+ i +1, A.begin () + i +3); }} t.insert ("()"+a); } } returnvector<string>(T.begin (), T.end ()); }};
Solution Two:
classSolution { Public: Vector<string> Generateparens (intN) {vector<string>Res; Generateparensdfs (n, N,"", RES); returnRes; } voidGenerateparensdfs (intLeftintRightstring out, vector<string> &Res) { if(Left > right)return; if(left = =0&& right = =0) Res.push_back ( out); Else { if(Left >0) Generateparensdfs (left-1, right, out+'(', RES); if(Right >0) Generateparensdfs (left, right-1, out+')', RES); } }};
[Careercup] 9.6 Generate parentheses generate parentheses