Problem
Given $n$ pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given $n$ = 3, a solution set is:
1 |
|
Explanation
- Draw a tree and find out the trend. For example, when the input is 3:
1 |
|
-
We notice that we can always add left paranthesis first until we have 3 left paranthesis.
-
When we have 3 left paranthesis, we can only add right paranthesis. Or, when the number of right parantheis is less than the number of left paranthesis, we can add right paranthesis.
-
The base case is when we have 3 right paranthesis, we need to return.
-
We can debug the solution.
Solution
1 |
|