Created
December 28, 2018 03:58
-
-
Save ehborisov/f98cf69606fa55625597c9c6390ba1b1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 parentheses_combinations_brute_force_1(n): | |
ans = [] | |
def generate_all(candidate): | |
if len(candidate) == 2 * n: | |
if is_valid(candidate): | |
ans.append(''.join(candidate)) | |
else: | |
candidate.append(')') | |
generate_all(candidate) | |
candidate.pop() | |
candidate.append('(') | |
generate_all(candidate) | |
candidate.pop() | |
generate_all([]) | |
return ans | |
def is_valid(candidate): | |
opening_brackets = 0 | |
closing_brackets = 0 | |
for s in candidate: | |
if s == '(': | |
opening_brackets += 1 | |
else: | |
closing_brackets += 1 | |
if closing_brackets > opening_brackets: | |
return False | |
return opening_brackets == closing_brackets | |
def parentheses_combinations_with_backtracking(n): | |
ans = [] | |
def generate_all(candidate, o, c): | |
print(candidate, o, c) | |
if o == c and o + c == 2*n: | |
ans.append(''.join(candidate)) | |
else: | |
if o + c < 2*n: | |
if o < n: | |
candidate.append('(') | |
generate_all(candidate, o + 1, c) | |
candidate.pop() | |
if c < o: | |
candidate.append(')') | |
generate_all(candidate, o, c + 1) | |
candidate.pop() | |
generate_all([], 0, 0) | |
return ans |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment