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