LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: Generate Parentheses

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:

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

The requirement for this question is to give n pairs of parentheses and generate all the correct combinations of parentheses.

The number of matching parentheses in the correct form should be generated. It is actually the catlan number, which is not detailed here.

Recursion can be used to output the correct combination of All parentheses. Use two variables, l and r, to record the number of left and right brackets. if and only if the left and right parentheses are 0, the end ends normally. Of course, there is another limit, that is, you can add the right parenthesis only when there are more left parentheses.

Time Complexity :??? (Number of results)

Spatial complexity :??? (Number of results)

1 class Solution 2 {3 private: 4 void generateParenthesis (vector <string> & v, string s, int l, int r) // l and r records the number of left and right parentheses 5 {6 if (l = 0 & r = 0) // when and only when the left and right parentheses are 0, normal end 7 v. push_back (s); 8 9 if (l> 0) 10 generateParenthesis (v, s + "(", l-1, r ); 11 if (r> 0 & l <r) // you can add the right brace 12 generateParenthesis (v, s + ")", l, r-1); 13} 14 public: 15 vector <string> generateParenthesis (int n) 16 {17 vector <string> v; 18 generateParenthesis (v, "", n, n); 19 return v; 20} 21 };

Reprinted, please describe the Source: LeetCode --- 22. 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.