Skip to content

Instantly share code, notes, and snippets.

@siddhantkushwaha
Created August 4, 2019 05:21
Show Gist options
  • Save siddhantkushwaha/e6b705bdee7b228e3f904a393b18fb0b to your computer and use it in GitHub Desktop.
Save siddhantkushwaha/e6b705bdee7b228e3f904a393b18fb0b to your computer and use it in GitHub Desktop.
Generate valid parantheses strings of length 2*n.
def solve(n, o, c, res):
if len(res) == 2*n:
yield res
if o > 0:
yield from solve(n, o-1, c, res+'(')
# derived from c > 0 and n-o > n-c
if c > o:
yield from solve(n, o, c-1, res+')')
solve(10, 10, 10, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment