# Java for Leetcode 022 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:

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

Problem solving idea One:

By observing the situation of n=2 and n=3 you can know that as long as the string at the beginning of the n=2, the end, ' (' Insert ' () ', attention to prevent duplication.

The Java implementation is as follows:

`static public list<string> generateparenthesis (int n) {hashset<string> set = new hashset<string> (); (n = = 1) set.add ("()"), if (n > 1) {arraylist<string> lastlist = new Arraylist<string> (Generateparenthesis ( n-1)); StringBuilder sb = new StringBuilder (); for (string string:lastlist) {sb = new StringBuilder (string); Set.add (Sb.tostring ( ) + "()"), Set.add ("()" + sb.tostring ()), for (int i = 0; i < sb.length ()-1; i++) {if (Sb.charat (i) = = ' (') {Sb.insert ( i + 1, "()"); Set.add (sb.tostring ());} SB = new StringBuilder (string);}} return new arraylist<string> (set);}`

Two ways to solve problems:

It can be observed that any parenthesis (n) that meets the conditions can always be decomposed into (generateparenthesis (k)) +generateparenthesis (n-1-k), Due to the uniqueness of the second half of Generateparenthesis (N-1-K), this algorithm does not produce duplicate elements, so it is more efficient to use DFS for a single traversal. The Java implementation is as follows:

`static public list<string> generateparenthesis (int n) {list<string> List = new arraylist<string> (), Leftlist, rightlist;if (n = = 0) list.add ("");//Critical, cannot delete if (n = = 1) list.add ("()"); else {for (int i = 0; I < n; i++) {leftlist = Generateparenthesis (i); rightlist = Generateparenthesis (N-i-1); for (String leftpart:leftlist) for (Stri ng Rightpart:rightlist) List.add ("(" + Leftpart + ")" + Rightpart);}} return list;}`

Java for Leetcode 022 Generate parentheses

Related Keywords:

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.