Generate Parentheses

Generate Parentheses

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def generateParenthesis(self, n, open=0):
"""
:type n: int
:rtype: List[str]
"""
if n == 0: return [')'*open]
if open == 0:
return ['(' + x for x in self.generateParenthesis(n - 1, 1)]
else:
return [')' + x for x in self.generateParenthesis(n, open - 1)] + ['(' + x for x in self.generateParenthesis(n - 1, open + 1)]
1
2
3
4
5
6
7
example for n = 2
else left branch:
( -> () -> ()( -> ()()
else right branch:
( -> (( -> (())

leet code