All problems
Generate Parentheses
Problem
Generate all strings of n pairs of balanced parentheses and return them as a list.
Backtrack by adding an opening parenthesis while fewer than n are open and a closing parenthesis while the number of closers is less than the number of openers. For n = 0 return a list containing only the empty string.
Hint
A closing parenthesis is only legal when more openers than closers have been placed.
Test cases
case 1
in: [0]
expected: [""]
case 2
in: [1]
expected: ["()"]
case 3
in: [2]
expected: ["(())","()()"]
case 4
in: [3]
expected: ["((()))","(()())","(())()","()(())","()()()"]
Starter codePython
def generate_parentheses(n):
# Your code here
pass4 test cases · run your code against them in the editor