Created
August 2, 2020 21:27
-
-
Save adamgarcia4/4a402a9ff569c853e459e610a02bcc24 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
class Solution: | |
def helper(self, numOpen, numClosed, n, solutionSoFar, result): | |
# Goal | |
if numOpen == n and numClosed == n: | |
result.append(solutionSoFar) | |
return | |
# Choice | |
# Choice 1: Place an open parenthesis | |
# Constraint on choice 1: When I have open parenthesis available to me. | |
if numOpen < n: | |
self.helper(numOpen + 1, numClosed, n, solutionSoFar + '(', result) | |
# Choice 2: Place a closed parenthesis | |
# Constraint on choice 2: I can only close an open parenthesis. (# open > # Closed) | |
if numOpen > numClosed: | |
self.helper(numOpen, numClosed + 1, n, solutionSoFar + ')', result) | |
def generateParenthesis(self, n: int) -> List[str]: | |
''' | |
n = 3 | |
Well Formed | |
()()() | |
(())() | |
Not Well Formed | |
())()( | |
)()()() | |
Optimization | |
Greedy approach (only if you can prove that the greedy choice leads to the optimal answer) | |
Do an "informed" exhaustive search. | |
Exhaustive Search | |
Generate All | |
Find All | |
Application | |
Permutations | |
Subsets | |
Combinations | |
numOpenToPlace: 2 | |
numClosedToPlace: 3 | |
1. Choices (2 choices) | |
I can Open a Parenthesis | |
I can Close a parenthesis | |
2. Constraint | |
I can open a parenthesis when: | |
When I have open parenthesis available to me. | |
I can close a parenthesis when: | |
I can only close an open parenthesis. | |
# open > # Closed | |
3. Goal | |
Place 'n' open parenthesis and 'n' closed parenthesis. | |
''' | |
result = [] | |
self.helper(0, 0, n, '', result) | |
return result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment