Generate N valid parentheses I

Given N pairs of parentheses “()”, return a list with all the valid permutations.

Assumptions

  • N > 0

Examples

  • N = 1, all valid permutations are ["()"]

  • N = 3, all valid permutations are ["((()))", "(()())", "(())()", "()(())", "()()()"]

Solution: Recursive DFS

Base Case: N left and N right parentheses have been made

Recursive rule:

  1. Add until N ' ( '

  2. Match with ' ) '

  3. delete previous ' ( '

  4. Match with ' ) '

Recursive Tree:

                                          (
                           ((                            ()
                      (((      (()                    ()(  
                ((()       (()(  (())             ()((   ()()
          ((())       (()()         (())(      ()(())      ()()(
   ((()))       (()())                (())()                   ()()()

Implementation:

Time complexity: O(2^parentheses * 2 * ) = O(2^2N * N)

Last updated

Was this helpful?