Created
October 13, 2020 13:16
-
-
Save JoshuaJakowlew/fb458513fe57b236db27683ce8db8275 to your computer and use it in GitHub Desktop.
Print all possible combinations of parenthesis in expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def print_parens(digits, s, n): | |
res = [] | |
def _print_parens(s, pos, n, open, close): | |
if(close == n): | |
for i in s: | |
print(i, end = "") | |
print() | |
res.append(''.join(s)) | |
else: | |
if(open > close): | |
s[pos] = ')' | |
_print_parens(s, pos + 1, n, open, close + 1) | |
if(open < n): | |
s[pos] = '(' + digits[open] | |
_print_parens(s, pos + 1, n, open + 1, close) | |
if(n > 0): | |
_print_parens(s, 0, n, 0, 0) | |
return res | |
digits = "123456" | |
n = len(digits) | |
s = [""] * 2 * n | |
res = print_parens(digits, s, n) | |
print(len(res)) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def print_parens(digits, s, n): | |
res = [] | |
def _print_parens(s, pos, n, open, close): | |
if(close == n): | |
for i in s: | |
print(i, end = "") | |
print() | |
res.append(''.join(s)) | |
else: | |
if(open > close): | |
s[pos] = ')' | |
_print_parens(s, pos + 1, n, open, close + 1) | |
if(open < n): | |
s[pos] = '(' + digits[open] | |
_print_parens(s, pos + 1, n, open + 1, close) | |
if(n > 0): | |
_print_parens(s, 0, n, 0, 0) | |
return res | |
digits = "123456" | |
n = len(digits) | |
s = [""] * 2 * n | |
res = print_parens(digits, s, n) | |
print(len(res)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment