forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-parentheses.py
30 lines (27 loc) · 940 Bytes
/
generate-parentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from __future__ import print_function
# Time: O(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
#
# 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:
#
# "((()))", "(()())", "(())()", "()(())", "()()()"
#
class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
result = []
self.generateParenthesisRecu(result, "", n, n)
return result
def generateParenthesisRecu(self, result, current, left, right):
if left == 0 and right == 0:
result.append(current)
if left > 0:
self.generateParenthesisRecu(result, current + "(", left - 1, right)
if left < right:
self.generateParenthesisRecu(result, current + ")", left, right - 1)
if __name__ == "__main__":
print(Solution().generateParenthesis(3))