LEETCODE22 Generate Parentheses Bracket generation

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:

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


Translation:

Give you an n, generate n set of parentheses, rules that conform to parentheses


Ideas:

This problem before the data structure has been done, and the number of the stack is related.

The name is called Cattleya number.

Baidu Encyclopedia Viki


Attach some Daniel's explanations about the number of Cattleya.

Http://www.cnblogs.com/wuyuegb2312/p/3016878.html

Next, say what I think. This problem can actually be done by hand. Each time the string is pressed into the list, the end condition is that both the left and right brackets have the remaining 0. And in the recursive process, the number of left parenthesis is greater than or equal to the right parenthesis.

Code:

    public static list<string> generateparenthesis (int n) {        list<string> ls = new arraylist<string> () ;        if (n <= 0)        return ls;        Gen (N,n, "", LS);                return ls;    } public static void  Gen (int l,int r,string s,list<string>ls) {if (R < L) return; if (L==0&&r = = 0) Ls.add (s); if (L > 0) gen (l-1,r,s+ ' (', LS); if (R > 0) gen (l,r-1,s+ ') ', LS);}





LEETCODE22 Generate Parentheses Bracket generation

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.