[leetcode]Generate Parentheses @ Python

原题地址:https://oj.leetcode.com/problems/generate-parentheses/

题意:

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

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

解题思路:列举出所有合法的括号匹配,使用dfs。如果左括号的数量大于右括号的数量的话,就不能产生合法的括号匹配。

代码:

class Solution:
    # @param an integer
    # @return a list of string
    # @draw a decision tree when n == 2, and you can understand it!
    def helpler(self, l, r, item, res):
        if r < l:
            return
        if l == 0 and r == 0:
            res.append(item)
        if l > 0:
            self.helpler(l - 1, r, item + '(', res)
        if r > 0:
            self.helpler(l, r - 1, item + ')', res)
    
    def generateParenthesis(self, n):
        if n == 0:
            return []
        res = []
        self.helpler(n, n, '', res)
        return res

 

    原文作者:南郭子綦
    原文地址: https://www.cnblogs.com/zuoyuan/p/3779797.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞