码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 22. Generate Parentheses

时间:2019-09-22 12:49:54      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:bin   set   div   app   function   help   res   func   The   

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:

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

Time: O(2^N)
Space: O(N)

 1 class Solution:
 2     def generateParenthesis(self, n: int) -> List[str]:
 3         res = []
 4         self.helper(0, 0, n, ‘‘, res)
 5         return res
 6     
 7     def helper(self, left, right, n, word, res):
 8         if left == n and right == n:
 9             res.append(word)
10         if left < n:
11             word += (
12             self.helper(left + 1, right, n, word, res)
13             word = word[:-1]
14         if left > right:
15             word += )
16             self.helper(left, right + 1, n, word, res)
17             word = word[:-1]

 

[LC] 22. Generate Parentheses

标签:bin   set   div   app   function   help   res   func   The   

原文地址:https://www.cnblogs.com/xuanlu/p/11566769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!