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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Train of thought: This problem if not analyze the law, it is difficult to come up with the answer to the law is if the number of left is greater than the number of right, you can add ') '; If the number of left is less than n, you can add ' ('. Using recursion, the recursive end condition is given first, and then it is deepened.
Code:
Public classSolution { PublicList<string> Generateparenthesis (intN) {List<String> list=NewArraylist<string>(); if(n<=0)returnlist; Generate (0, List, 2*n, "", 0, 0); SYSTEM.OUT.PRINTLN (list); returnlist; } Public voidGenerateintIndex,list<string> List,intSize,string STR,intLeftintRight ) { if(index==size) {List.add (str); return; } Index++; if(left>Right ) generate (index, list, size, str+ ') ', left, right+1); if(LEFT<SIZE/2) Generate (index, list, size, str+ ' (', left+1, right); }}
[Leetcode] Generate parentheses