hnOsmium0001

leetcode Generate Parentheses

Jul 15th, 2021
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. const solutions = [];
  2.  
  3. /**
  4. * @param {number} n
  5. * @return {string[]}
  6. */
  7. var generateParenthesis = function(n) {
  8. return gen(n).filter(s => s.length > 0).sort();
  9. }
  10.  
  11. // WTF is this problem
  12. // the result needs to be sorted as given
  13. function gen(n) {
  14. if(n <= 0) {
  15. return [''];
  16. }
  17. if(n === 1) {
  18. return ["()"];
  19. }
  20. if(solutions[n]) {
  21. return solutions[n];
  22. }
  23.  
  24. const result = [];
  25. // First: standby (nothing inside) (0, n-1)
  26. // Wrapped + standby
  27. // Last: wrapped (nothing after) (n-1, 0)
  28. for(let i = 0, k = n - 1; i <= k; ++i) {
  29. for(const s1 of gen(i)) {
  30. for(const s2 of gen(k - i)) {
  31. result.push(`(${s1})${s2}`)
  32. }
  33. }
  34. }
  35. solutions[n] = result;
  36. return result;
  37. };
  38.  
Add Comment
Please, Sign In to add comment