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:
"((()))", "(()())", "(())()", "()(())", "()()()"
The first thing that comes to mind when you see this is the Catlan number, according to Catlan numbers, we know that the final solution is Catlan.
Here we are asked to solve we can use BFS enumeration to resolve.
1. Add an opening parenthesis when the number of opening brackets is less than n
2. Add a closing parenthesis when the number of parentheses is less than the opening parenthesis
3. When the total bracket length equals 2n, the solution is added to the set of solutions.
This is a catlan number problem. We can know the final solution length is the corresponding Catlan number.
To give specific solutions
1. When # of left parentheses are no greater than n we append left parentheses
2. When # of right parentheses are not greater than left parentheses we append right parentheses
3. When the total length was 2n we append it to solution
Code is as follow:
Class solution: # @param an integer # @return A list of string def FINDP (Self,valuelist,solution,n,left, right): If Len (valuelist) ==2*n: solution.append (valuelist) if left<n: SELF.FINDP (valuelist+ ' ( ', solution,n,left+1,right) if right<left: SELF.FINDP (valuelist+ ') ', solution,n,left,right+1) def Generateparenthesis (self, N): solution=[] SELF.FINDP (", solution,n,0,0) return solution
Generate parentheses Leetcode Python