Leetcode:generate parentheses

Source: Internet
Author: User

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: Two methods are introduced here, one is recursive construction and the other is DFS.

1. Recursive method

This method is simple and straightforward, but to understand how it is constructed, n pairs of valid parentheses can be constructed by means of I (0=< I <= n-1) to the effective bracket pair inner and n-1-i to the effective bracket pair outer, "(" +inner+ ")" +outer, and no duplicates.

classSolution { Public: Vector<string> Generateparenthesis (intN) {if(n = =0)returnvector<string> (1,""); if(n = =1)returnvector<string> (1,"()"); Vector<string>result;  for(inti =0; I < n; i++){             for(Auto Inner:generateparenthesis (i)) for(Auto Outer:generateparenthesis (n1-i)) Result.push_back ("("+ Inner +")"+outer); }        returnresult; }};

2. You can also use DFS solver to always guarantee the number of "(" greater than or equal to ") during the build process.

classSolution { Public: Vector<string> Generateparenthesis (intN) {vector<string>result; if(N >0) Generate (N,"",0,0, result); returnresult; }        voidGenerateintNstringSintLintR, vector<string> &result) {        if(L = =N) {result.push_back (S.append (n-R,')')); return; } generate (n, S+'(', L +1, R, result); if(L > R) Generate (n, S +")", L, R +1, result); }};

Leetcode:generate parentheses

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.