imashutosh51

Generate all valid parenthesis of length k

Jul 23rd, 2022 (edited)
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.71 KB | None | 0 0
  1. '''
  2. The time complexity looks like 2^n as there are two options either select open or close, but actually it is not because you can't add close before open so some pruning happened and it brought the number to catalan number(total number of valid parenthesis of n size) and n for each string to build so Catalan number*N is the time compleixty.
  3. explore catalan number proof in more detail.
  4. '''
  5.  
  6. #M-1 for better time complexity
  7. def fun(cur, open_cnt, close_cnt, n, ans):
  8.     if open_cnt == close_cnt == n:
  9.         ans.append(cur)
  10.         return
  11.  
  12.     if open_cnt < n:
  13.         fun(cur + '(', open_cnt + 1, close_cnt, n, ans)
  14.  
  15.     if close_cnt < open_cnt:
  16.         fun(cur + ')', open_cnt, close_cnt + 1, n, ans)
  17.  
Advertisement
Add Comment
Please, Sign In to add comment