Skip to content

Instantly share code, notes, and snippets.

@anhldbk
Created March 26, 2017 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anhldbk/1650c0d0306a9f20b7e721f62c2b1bb1 to your computer and use it in GitHub Desktop.
Save anhldbk/1650c0d0306a9f20b7e721f62c2b1bb1 to your computer and use it in GitHub Desktop.
Print all combinations of balanced parentheses
def fill(array, pos, count = 0):
max_count = len(array) / 2
if pos >= len(array ):
if count == 0:
print array
return
label = {
1: '{',
-1: '}'
}
for i in [-1,1]:
if count + i < 0:
continue
if count + i > max_count:
continue
array[pos] = label[i]
count += i
pos += 1
fill(array, pos,count)
count -= i
pos -= 1
array = ['*'] * 6
count = 0
pos = 0
fill(array, count, pos)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment