-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_parentheses.py
More file actions
32 lines (28 loc) · 847 Bytes
/
generate_parentheses.py
File metadata and controls
32 lines (28 loc) · 847 Bytes
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
# 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:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
"""
>>> generate_parentheses(0)
['']
>>> generate_parentheses(3)
['((()))', '(()())', '(())()', '()(())', '()()()']
"""
from typing import List
def generate_parentheses(num_of_pairs_parentheses: int) -> List[str]:
result = []
backtracking(num_of_pairs_parentheses, result)
return result
def backtracking(n, result, left=0, right=0, parentheses=''):
if len(parentheses) == n * 2:
return result.append(parentheses)
if left < n:
backtracking(n, result, left + 1, right, parentheses + '(')
if right < left:
backtracking(n, result, left, right + 1, parentheses + ')')