您的位置:首页 > 编程语言 > Python开发

[leetcode]Generate Parentheses @ Python

2014-06-10 13:25 260 查看
原题地址: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: