[LC] 22. Generate Parentheses

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 22. 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:

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

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的主要内容,如果未能解决你的问题,请参考以下文章

22. Generate Parentheses(ML)

LeetCode - 22. Generate Parentheses

LeetCode 22. Generate Parentheses

Leetcode 22. Generate Parentheses

22. Generate Parentheses

22. Generate Parentheses(js)