Generate parentheses Leetcode Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.