Generate Parentheses @ LeetCode

Source: Internet
Author: User

Package Level3; import java. util. arrayList;/*** 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 :"((()))","(()())","(())()", "()", "()" **/public class S22 {public static void main (String [] args) {System. out. println (generateParenthesis (3);} public static ArrayList <String> generateParenthesis (int n) {ArrayList <String> list = new ArrayList <String> (); rec (n, 0, 0, "", list); return list;} public static void rec (int n, int left, int right, String s, ArrayList <String> list) {// The number of invariant must be greater than or equal to the number of right brackets. if (left <right) {return ;} // If the left and right parentheses are equal, add them to listif (left = n & right = n) {list. add (s); return;} // The left parenthesis is full. You can only add the right brace if (left = n) {rec (n, left, right + 1, s + ") ", list); return;} rec (n, left + 1, right, s +" (", list); // Add the left brace rec (n, left, right + 1, s + ")", list); // Add another right bracket }}

 

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.