22--leetcode--括號生成

給出 n 代表生成括號的對數,請你寫出一個函數,使其能夠生成所有可能的並且有效的括號組合。

例如,給出 n = 3,生成結果爲:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

 

class Solution(object):
    def generateParenthesis(self, n):
        ans=[]
        def function(s='',l=0,r=0):
            if len(s)==2*n:
                ans.append(s)
                return                               #注意返回條件
            if l<n:
                function(s+'(',l+1,r)            #倆個if並列
            if r<l:
                function(s+')',l,r+1)
        function()
        return ans

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章