1 classSolution {2 Public:3vector<string> Generateparenthesis (intN) {4vector<string>result;5 stringCurrent ;6 stringChoice ="()";7 intNumleftbracket =0;//count, the difference between the opening parenthesis and the closing parenthesis, just the number of opening brackets in the string is always not less than the number of closing parentheses, and the length is limited8 DFS (result, choice, current, n, numleftbracket);9 returnresult;Ten } One Private: A voidDFS (vector<string>& result,Const string& Choice,string& Current,intNintnumleftbracket) - { - if(Numleftbracket = =0&& current.size () = = n *2) { the Result.push_back (current); - return; - } - Else { + if(Numleftbracket <0|| Numleftbracket > N | | Current.size () > N *2)returnyou need to pay attention to limiting the current length . - Else { + for(inti =0; I < choice.size (); ++i) { A if(Numleftbracket >0) { at Current.push_back (Choice[i]); - if(Choice[i] = ='(') Dfs (result, choice, current, N, Numleftbracket +1); - ElseDFS (result, choice, current, N, Numleftbracket-1); - } - Else { - if(Choice[i] = =')')Continue; in Else { - Current.push_back (Choice[i]); toDFS (result, choice, current, N, Numleftbracket +1); + } - } the Current.pop_back (); * } $ }Panax Notoginseng } - } the};
022. Generate parentheses