Skip to content

Commit 4a7bf03

Browse files
Added Printing Parentheses cominations problem from CTCI
1 parent 2853fd6 commit 4a7bf03

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Print all valid (properly opened and closed) combinations of n pairs of parentheses.
3+
"""
4+
5+
6+
def addParentheses(str_arr, leftParenCount, rightParenCount, combinations, index):
7+
if leftParenCount < 0 or rightParenCount < 0:
8+
return
9+
if leftParenCount == 0 and rightParenCount == 0:
10+
combinations.append(''.join(str_arr))
11+
else:
12+
if leftParenCount > 0:
13+
str_arr[index] = '('
14+
addParentheses(str_arr, leftParenCount - 1, rightParenCount, combinations, index + 1)
15+
16+
if rightParenCount > leftParenCount:
17+
str_arr[index] = ')'
18+
addParentheses(str_arr, leftParenCount, rightParenCount - 1, combinations, index + 1)
19+
20+
21+
def generateParentheses(count):
22+
str_arr = [''] * (count * 2)
23+
combinations = []
24+
addParentheses(str_arr, count, count, combinations, 0)
25+
return combinations
26+
27+
28+
parenthesis_pairs = 3
29+
combinations = generateParentheses(parenthesis_pairs)
30+
print(*combinations, sep=', ')

0 commit comments

Comments
 (0)