generate parentheses

这道题是backtracking的一点变形,第一次没做出来,其实就是在普通backtracking的时候,不用loop,而是列举出所有的情况。

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
class (object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
self.dfs(0, 0, n, [], res)
return res
def dfs(self, count_left, count_right, n, cur, res):
if count_right == n:
res.append("".join(cur))
return
if count_right < count_left and count_left < n:
cur.append("(")
self.dfs(count_left+1, count_right, n, cur, res)
cur.pop()
cur.append(")")
self.dfs(count_left, count_right+1, n, cur, res)
cur.pop()
elif count_right == count_left and count_left < n:
cur.append("(")
self.dfs(count_left+1, count_right, n, cur, res)
cur.pop()
elif count_right < count_left and count_left == n:
cur.append(")")
self.dfs(count_left, count_right+1, n, cur, res)
cur.pop()