21. Generate Parentheses Leetcode Python


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:
"((()))", "(()())", "(())()", "()(())", "()()()"
この問題を見てまず思いついたのはcatlan Numberですcatlan numberによると最後の解の数はcatlan numberであることがわかります
ここではbfs列挙で解決できることを解く必要がある.
1.左かっこの数がnより小さい場合に左かっこを追加
2.括弧の数が左括弧より小さい場合は右括弧を追加
3.全括弧長が2 nに等しい場合、解は解の集合に加えられる.
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 is no greater than n we append left parentheses
2. when # of right parentheses is not greater than left parentheses we append right parentheses
3. when the total length is 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