Let's examine a scenario where n = 3 . One possible approach to tackle this issue using DFS is as follows: def generateParenthesis ( n ) : def generate ( p , left , right , parens = [ ] ) : if left : generate ( p + '(' , left - 1 , right ) if right > left : generate ( p + ')' , left , right - 1 ) if not right : parens . append ( p ) return parens return generate ( '' , n , n ) This code keeps track of the number of left and right parentheses remaining that can still be used. If there are left parentheses available to place at the current location, we insert one. If the count of right parentheses exceeds that of left parentheses, we can then add a closing parenthesis.