Generate parentheses--Problem Solving report

Source: Internet
Author: User


Topic

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:

"((()))", "(()())", "(())()", "()(())", "()()()"



Analysis

is obviously a traversal process, but how to traverse is a problem. Traversal, we can often use recursion to solve. Recursion, the routine is to write out the conditions first, and then write the other recursive calling program part. the exit condition of this topic is obviously when the left parenthesis (and the closing parenthesis) are all used up, the results are pressed back in. What about the rest of it? This time will be combined with specific problems, specific analysis. parentheses match the core, the resulting parentheses must be well-formed. This requires the currently generated cur string, so be sure that the number of opening parentheses is less than the number of closing parentheses. Therefore, if the number of opening brackets m is not equal to 0, you can continue placing, and when the number of opening parentheses is less than the number of closing brackets, and the number of closing parentheses is not equal to 0, the closing parenthesis can be placed!



Code

Running time: 5ms


Class Solution {public:    vector<string> generateparenthesis (int n) {        vector<string> res;        if (n = = 0)            return res;                    String cur = "";        Fun (res, cur, n, n);                return res;    }        void Fun (vector<string>& res, string cur, int m, int n)    {        if (m = = 0 && n = = 0)        {            res . push_back (cur);            return;        }                if (M! = 0)        {fun            (res, cur + ' (', m-1, n);        }        if (M < n && n! = 0)  //"M < n" Ensure the generated parantheses is well-formed        {fun            (res, CU R + ') ', M, n-1);}}            ;


Generate parentheses--Problem Solving report

Related Article

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.