-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22.generateParenthesis.py
56 lines (40 loc) · 1.3 KB
/
22.generateParenthesis.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
# Example 1:
# Input: n = 3
# Output: ["((()))","(()())","(())()","()(())","()()()"]
# Example 2:
# Input: n = 1
# Output: ["()"]
# Constraints:
# 1 <= n <= 8
from typing import List
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
# only add open prenthesis if open < n
# only add close prenthesis if close < open
stack = []
result = []
def backtrack(openN, closedN):
if openN == closedN == n:
result.append("".join(stack))
return
if openN < n:
stack.append("(")
backtrack(openN + 1, closedN)
stack.pop()
if closedN < openN:
stack.append(")")
backtrack(openN, closedN + 1)
stack.pop()
backtrack(0, 0)
return result
if __name__ == "__main__":
s = Solution()
print(s.generateParenthesis(3))
# print(s.generateParenthesis(1))
# print(s.generateParenthesis(2))
# print(s.generateParenthesis(4))
# print(s.generateParenthesis(5))
# print(s.generateParenthesis(6))
# print(s.generateParenthesis(7))
# print(s.generateParenthesis(8))