Title Description:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Problem Solving Analysis:
This kind of problem usually has to be solved by recursive method. You need to set up two collection classes to store the number of (,) to be matched respectively.
It is important to understand that only matches (which are never smaller than the number of matches to be matched) can be matched (or cause an error.) (You can try it yourself on paper to understand it), the rest of the situation can be considered to match (and) the possible results in both cases.
Specific code:
1 Public classSolution {2 Public StaticList<string> Generateparenthesis (intN) {3list<string> result =NewArraylist<string>();4List<character> array1=NewLinkedlist<character>();5List<character> array2=NewLinkedlist<character>();6 Char[] Array =New Char[n];7 for(inti=0;i<n;i++){8Array1.add (' (');9Array2.add (') ');Ten } OneFUN1 (array1,array2,result,array,0); A returnresult; - } - Public Static voidFUN1 (list<character> array1,list<character> array2,list<string> result,Char[] Array,intindex) { the if(index==array.length-1){ - if(Array1.size () ==0&&array2.size () ==1){ -Array[index]=array2.remove (0); -Result.add (NewString (array)); +Array[index]= "; -Array2.add (') '); + return; A } at Else{ - return; - } - } - //only fill in ' (' - if(Array1.size () >=array2.size ()) { inArray[index]=array1.remove (0); -FUN1 (array1,array2,result,array,index+1); toArray[index]= "; +Array1.add (' ('); - } the Else{ * //first Try ' (' $ if(Array1.size () >0){Panax Notoginseng -Array[index]=array1.remove (0); theFUN1 (array1,array2,result,array,index+1); +Array[index]= "; AArray1.add (' ('); the } + //try Again ') ' -Array[index]=array2.remove (0); $FUN1 (array1,array2,result,array,index+1); $Array[index]= "; -Array2.add (') '); - } the - }Wuyi}
"Leetcode" 22. Generate parentheses