Generate Parentheses

Try to solve the Generate Parentheses problem.

Statement#

For a given number, n, generate all combinations of balanced parentheses.

Constraints:

  • 11 \leq n 10\leq 10

Examples#

Created with Fabric.js 3.6.6 Input Output Sample example 1 n = 3

1 of 2

Created with Fabric.js 3.6.6 Input Output Sample example 2 n = 4

2 of 2

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Generate Parentheses

1

Which is a valid combination of balanced parentheses when n = 2?

A)

()()

(())

((()

B)

(())

))((

()()

C)

()()

(())

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Create an output list to store all the valid combinations of parantheses.

Call the back_track function with initial parameters set to n, empty string and 0 for the count of both, opening and closing parantheses.

If the count of opening and closing parentheses equals n, then we have a valid combination of parentheses, so we will append the string to our final list.

Otherwise, we will check if the number of opening parentheses is less than n. If yes, we will add opening parentheses to our string and increment the count.

Lastly, we will check the count of closing parentheses. If the count is less than the count of opening parentheses, then we will add closing parentheses to our string and increment its count.


Try it yourself#

Implement your solution in main.py in the following coding playground. We have provided a useful code template in the other file, that you may build on to solve this problem.

Python
main.py
backtracking.py
Input #1
Generate Parentheses

Solution: Letter Combinations of a Phone Number

Solution: Generate Parentheses