Leetcode--22. Bracket generation

Source: Internet
Author: User

A period of time did not write, and then into the leetcode found in the Chinese area of the site.

Title: 22. Bracket generation

Link: https://leetcode-cn.com/problems/generate-parentheses/description/

Given a positive integer n, all valid combinations of n pairs of parentheses are required. Always consider a pair of parentheses together, and add a pair on the basis of the N-1 bracket, so that when the n=4 is less (()) (()), the subsequent recursive result is naturally less. Here are the thoughts of others:

The opening and closing brackets are considered separately, with the number left and right represented (note that the first must be an opening parenthesis). When the number of opening parentheses is left<n, add an opening parenthesis, where the number of right parenthesis is less than left, you can add a closing parenthesis. When Left>=n, only the closing parenthesis is added. The recursive termination condition is left+right==2*n, at which point the combination is added to the result set.

Python code:

Class Solution (object): Def generateparenthesis (self, N): "": Type N:int:rtype:list[str]             "" # def Getans (n, res, ans): # if n = 0: # If res not in ans: #
        Ans.add (RES) # return # Else: # Getans (n-1, res + "()", ans) # Getans (N-1, "() + res, ans) # Getans (N-1," ("+ res +"), ans) # # A NS = set () # Getans (N, ", ans) def getret (n, left, right, ret, ans): if left + right = n * 2:ans.add (ret) return if left < N:getret (n, left + 1, rig
            HT, ret + "(, ans) if right < Left:getret (n, left, right + 1, ret +"), ans) Else:getret (n, left, right + 1, ret + ")", ans) ans = set () Getret (n,0,0, "", ans ) return list (Ans 

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.