[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:

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

Train of thought: This problem if not analyze the law, it is difficult to come up with the answer to the law is if the number of left is greater than the number of right, you can add ') '; If the number of left is less than n, you can add ' ('. Using recursion, the recursive end condition is given first, and then it is deepened.

Code:

 Public classSolution { PublicList<string> Generateparenthesis (intN) {List<String> list=NewArraylist<string>(); if(n<=0)returnlist; Generate (0, List, 2*n, "", 0, 0);        SYSTEM.OUT.PRINTLN (list); returnlist; }     Public voidGenerateintIndex,list<string> List,intSize,string STR,intLeftintRight ) {        if(index==size)            {List.add (str); return; } Index++; if(left>Right ) generate (index, list, size, str+ ') ', left, right+1); if(LEFT&LT;SIZE/2) Generate (index, list, size, str+ ' (', left+1, right); }}

[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.