Generate parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution One: Recursion
With Stacks, ' (', ') ' constitutes a pair of separate entry and exit stacks. When the last stack is empty, the input parentheses make up a string that is legal.
classSolution { Public: Vector<string> Generateparenthesis (intN) {vector<string>result; if(n = =0) returnresult; //First must be ' (' stringCur ="("; Stack<Char>s; S.push ('('); Helper (result, cur, s,2*n-1); returnresult; } voidHelper (vector<string>& result,stringCur, stack<Char> S,intnum) { if(num = =1) {//must be ') ' if(S.top () = ='('&& s.size () = =1) {//All matchedCur + =')'; Result.push_back (cur); } } Else { //' (' Always push stringSTR1 =cur; STR1+='('; S.push ('('); Helper (result, STR1, S, Num-1); S.pop (); //' ) ' if(!S.empty ()) {//prune. Never begin with ') ' stringSTR2 =cur; STR2+=')'; if(S.top () = ='(') S.pop (); //check Empty () before access top () ElseS.push (')'); Helper (result, STR2, S, Num-1); } } }};
Solution Two: Recursion
A little analysis shows that the stack is unnecessary, as long as there are several ' (', Count ') records in the string.
Each entry into a ' (', Count + +.) Each matching pair of parentheses, Count--。
Eventually all match, need count==0
classSolution { Public: Vector<string> Generateparenthesis (intN) {vector<string>result; if(n = =0) returnresult; //First must be ' (' stringCur ="("; intCount =1;//Number of (' s in curHelper (result, cur, count,2*n-1); returnresult; } voidHelper (vector<string>& result,stringCurintCountintnum) { if(num = =1) {//must be ') ' if(Count = =1) {//All matchedCur + =')'; Result.push_back (cur); } } Else { //' (' Always push stringSTR1 =cur; STR1+='('; Count++; Helper (result, str1, count, Num-1); Count--; //' ) ' if(Count! =0) {//prune. Never begin with ') ' stringSTR2 =cur; STR2+=')'; Count--; Helper (result, str2, count, Num-1); } } }};
"Leetcode" Generate parentheses (2 solutions)