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