Leetcode:generate parentheses

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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

Thinking Analysis:
The final combination results always have the same rule: the number of opening parentheses is greater than or equal to the number of closing parentheses. So, according to this rule: suppose that the left parenthesis and right parenthesis are left in position K, and if left>0, the opening parenthesis can be printed directly. , if Left<right and right!=0, you can print the closing parenthesis. If both left and right are zero, then a legal arrangement has been completed to print it out.

C + + Reference code:

classsolution{Private:voidGeneratesub ( vector<string>&result,stringCurrentintLeftintright) {if(left = =0&& right = =0) Result.push_back (current);Else{if(Left! =0) generatesub (result, current +' (', left-1, right);if(Left < right && right! =0) generatesub (result, current +' ) ', left, right-1); }    } Public: vector<string>Generateparenthesis (intN) { vector<string>Resultif(N >0) Generatesub (Result,string(), n, N);returnResult }};

C # Reference Code:

 Public classsolution{Private void generatesubstring(ilist<string> result,stringCurrentintLeftintright) {Stringvalue= current;if(left = =0&& right = =0) result. ADD (value);Else{if(Left! =0) generatesubstring (result, current +' (', left-1, right);if(Left < right && right! =0) generatesubstring (result, current +' ) ', left, right-1); }    } Publicilist<string>generateparenthesis(intN) {ilist<string> result =Newlist<string> ();if(N >0) generatesubstring (Result,"", N, N);returnResult }}

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.