-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbalancedParentheses.py
35 lines (31 loc) · 1.18 KB
/
balancedParentheses.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
def getBalancedParens(pairs, openRem=None, closeRem=None, current='', indent=0):
if openRem is None:
openRem = pairs
if closeRem is None:
closeRem = pairs
print('.' * indent, end='')
print('Start of pairs=' + str(pairs) + ', openRem=' + str(openRem) +
', closeRem=' + str(closeRem) + ', current="' + current + '"')
if openRem == 0 and closeRem == 0:
# BASE CASE
print('.' * indent, end='')
print('1st base case. Returning ' + str([current]))
return [current]
# RECURSIVE CASE
results = []
if openRem > 0:
print('.' * indent, end='')
print('Adding open parenthesis.')
results.extend(getBalancedParens(pairs, openRem - 1, closeRem,
current + '(', indent + 1))
if closeRem > openRem:
print('.' * indent, end='')
print('Adding close parenthesis.')
results.extend(getBalancedParens(pairs, openRem, closeRem - 1,
current + ')', indent + 1))
# BASE CASE
print('.' * indent, end='')
print('2nd base case. Returning ' + str(results))
return results
print('All combinations of 2 balanced parentheses:')
print('Results:', getBalancedParens(2))