码迷,mamicode.com
首页 > 编程语言 > 详细

21. Generate Parentheses Leetcode Python

时间:2015-01-29 12:43:04      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   bfs   

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.当总括号长度等于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

标签:leetcode   python   bfs   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/43268855

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!