【LeetCode】22. 生成括号

问题描述

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

给定n对括号,编写一个函数来生成所有形式良好的括号组合。

比如,给定 n = 3,则输出结果应为:

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

Python 实现

显然,这种配对问题使用递归的方法来实现是最直观的。根据题目的条件,需要满足的几个基本条件是:

  1. 形式良好的组合,必须满足左括号与右括号之和等于n*2;
  2. 左括号数量不能大于n;
  3. 右括号不能多于左括号。

因此,在未得到最终组合之前,我们可以向字符串内添加 “(” 或者 “)” 。由于向 res 列表添加组合字符串的操作是在最深一层递归调用中实现的,所以当向上一级调用返回时,实际上蕴含一个回溯的思想,即回到上一级的状态,然后执行不同的操作,从而得到其他形式的组合结果。具体代码实现如下:

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        
        if not n:
            return None
        res = []
        self.generate(0, 0, n, "", res)
        return res
        
    def generate(self, left, right, n, string, res):
        # Required result.
        if left+right == 2*n:
            res.append(string)
            return
        
        # Recursive Step.
        if left < n:
            self.generate(left+1, right, n, string+"(", res)
        
        if left > right:
            self.generate(left, right+1, n, string+")", res)
    
        

链接:https://leetcode.com/problems/generate-parentheses/

发布了49 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/sinat_36645384/article/details/105323385
今日推荐