Skip to content

Instantly share code, notes, and snippets.

@adamgarcia4
Created August 2, 2020 21:27
Show Gist options
  • Save adamgarcia4/4a402a9ff569c853e459e610a02bcc24 to your computer and use it in GitHub Desktop.
Save adamgarcia4/4a402a9ff569c853e459e610a02bcc24 to your computer and use it in GitHub Desktop.
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