"((()))", "(()())", "(())()", "()(())", "()()()"
看到这道题目首先想到的是catlan Number 根据catlan number我们可以知道最后的解的数量是catlan number
这里要求我们求解我们可以用bfs枚举来解决。
1.当左括号数量小于n 时候添加左括号
2.当有括号数量小于左括号时候添加右括号
3.当总括号长度等于2n时候将解加入解的集合。
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
21. Generate Parentheses Leetcode Python
原文地址:http://blog.csdn.net/hyperbolechi/article/details/43268855