fork(40) download
  1. S = input()
  2. N = len(S)
  3.  
  4. memo = {}
  5.  
  6. def go(last,o):
  7. # *count* all *valid* suffixes for the current subsequence
  8. # assuming that S[last] was the last character used
  9. # and we currently have o opened parentheses
  10.  
  11. # if we already solved this, recall the result
  12. if (last,o) in memo: return memo[ (last,o) ]
  13.  
  14. # if everything got closed, we can end right where we are
  15. if o==0: answer = 1
  16. else: answer = 0
  17.  
  18. # we can always try adding another '('
  19. nextl = last+1
  20. while nextl<N and S[nextl] != '(': nextl += 1
  21. if nextl<N: answer += go(nextl,o+1)
  22.  
  23. # only if o>0, we can also try adding another ')'
  24. if o>0:
  25. nextr = last+1
  26. while nextr<N and S[nextr] != ')': nextr += 1
  27. if nextr<N: answer += go(nextr,o-1)
  28.  
  29. # and that's it -- but don't forget to remember :)
  30. memo[ (last,o) ] = answer
  31. return answer
  32.  
  33. print(go(-1,0))
Success #stdin #stdout 0.1s 10088KB
stdin
())(())()())()()()))))()(()()))()()()()()()()())
stdout
14150760