首页 > 代码库 > 21. Generate Parentheses Leetcode Python
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:
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
看到这道题目首先想到的是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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。