educative.io

Recursive solution with less parameters

Here is the python solution which has less parameters. My idea is that we either add parentheses pair to the left or to the right or wrap the result.

def generate_valid_parentheses(parenthesesCount):
  result = []
  rec(parenthesesCount, '', result, True)
  return result

# 'notNested' indicates that the previousString does not have any nested parentheses
# This will help avoid duplication s. E.g. for '()' we'll only have one '()()'
def rec(parenthesesCount, previousString, result, notNested):
  if parenthesesCount == 0:
    result.append(previousString)
    return
  
  rec(parenthesesCount - 1, '()' + previousString, result, notNested)
  
  if not notNested:
    rec(parenthesesCount - 1, previousString + '()', result, False)
  if path != '':
    rec(parenthesesCount - 1, '(' + previousString + ')', result, False)