Given
Output: ["((()))","(()())","(())()","()(())","()()()"]
Output: ["()"]
Constraints:
0 <= n <= 8
Contents
Solution 1 - Using Backtracking
In this approach, we are going to apply
-
A valid parenthesis always have to start with an opening bracket
'(' . -
When there are equal number of opening and closing brackets, but current brackets count is less than
n , then next bracket should be an opening bracket. For example, sayn = 3 and current parentheses are()() or(()) , next bracket should be an opening bracket( otherwise, it will make it invalid parentheses.
Let's look at an example with n=3, when we apply above rules, decision tree will look like this, at each level we will check with both possibilities of adding
a left bracket
Implementation steps:
-
First, we will create a helper function that we are going to call recursively, that takes following arguments.
-
n , input parameter. -
openN , number of open brackets in current parentheses. -
closeN , number of close brackets in current parentheses. -
stack , stack of characters in current parentheses, reason we choseStack is because at each step we will try with possibilities of an opening and closing brackets, after trying one option (considering an opening bracket) we will remove the top element and try with other option (considering closing bracket). -
result , resultList that we will add the output into.
-
-
Next, check if we hit the base case. That is if
openN count is equal tocloseN and they are also equal ton , this means we have used all choices of opening and closing brackets, now we can construct a string out of the characters fromstack and add toresult list. -
Then, check if
openN < n , this means that opening bracket choice is possible, so add the current character'(' intostack and call this helper function recursively, once this loop ended, remove the top element from stack. -
Then, check if
closeN < openN , this means that we can consider a closing bracket, so add the current character')' intostack and call this helper function recursively, once this loop ended, remove the top element from stack. -
Call above helper function with inputs
n ,0 ,0 ,empty stack andempty result list .
Complexity Analysis:
Time complexity: Above code runs in O(2n) since we are calling helper function recursively, with all possibilities.
Space complexity: O(n), since we are calling the helper function recursively, this is the memory used by memory stack.
Above implementations source code can be found at