首页 > 其他 > 详细

leetcode22 Generate Parentheses

时间:2020-02-15 11:51:15      阅读:61      评论:0      收藏:0      [点我收藏+]
 1 """
 2  Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
 3 For example, given n = 3, a solution set is:
 4 [
 5   "((()))",
 6   "(()())",
 7   "(())()",
 8   "()(())",
 9   "()()()"
10 ]
11 """
12 """
13 每次增加括号时需要判断之前字符串中左右括号的个数
14 判断增加‘(’或‘)’依据为,
15 #若当前字符串的长度等于2n则字符串存入列表中
16 若之前字符串中左括号个数小于n,则应增加左括号,
17 若之前字符串中右括号个数小于左括号,则应增加右括号
18 """
19 class Solution:
20     def generateParenthesis(self, n):
21         result = []
22         # 函数嵌套
23         def trackback(S="", left=0, right=0):
24             if len(S) == 2 * n:
25                 result.append(S)
26             if left < n:
27                 trackback(S + (, left + 1, right)
28             if right < left:
29                 trackback(S + ), left, right + 1)
30         trackback()
31         return result

 

leetcode22 Generate Parentheses

原文:https://www.cnblogs.com/yawenw/p/12310874.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!