"Leetcode" Generate parentheses (2 solutions)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.