-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_0022.py
31 lines (22 loc) · 1000 Bytes
/
leetcode_0022.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
class Solution:
def generateParenthesis(self, n: int) -> list[str]:
results: list[str] = []
def backtracking(num: int, current: str, stack: int):
if num == 0:
results.append(current + ")" * stack)
return
# Add an open parenthesis
backtracking(num - 1, current + "(", stack + 1)
# Add a close parenthesis if valid
if stack > 0:
backtracking(num, current + ")", stack - 1)
backtracking(n, "", 0)
return results
s = Solution()
print(s.generateParenthesis(n=1)) # ["()"]
print(s.generateParenthesis(n=2)) # ["(())", "()()"]
# ["((()))","(()())","(())()","()(())","()()()"]
print(s.generateParenthesis(n=3))
# ['(((())))', '((()()))', '((())())', '((()))()', '(()(()))', '(()()())', '(()())()', '(())(())', '(())()()', '()((()))', '()(()())', '()(())()', '()()(())', '()()()()']
print(s.generateParenthesis(n=4))
# print(s.generateParenthesis(n=10))