22.括号生成

生成括号个数为n的合法的括号组合

思路:回溯,这题官方解法的dfs函数特别简单,值得看

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        ans = []
        res = ''
        def dfs(l_num,r_num,res):
            if l_num == 0 and r_num == 0:
                ans.append(res)
                return
            if l_num>0:
                dfs(l_num-1,r_num,res+'(')
            if r_num>l_num:
                dfs(l_num,r_num-1,res+')')
        dfs(n,n,res)  
        return ans

你可能感兴趣的:(22.括号生成)