code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

11 Generate Parentheses

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const generateParentheses = n => {
  const result = []
  const backtrack = (curr, left, right) => {
    if (left == 0 && right == 0) {
      result.push(curr)
      return
    }
    if (left > 0) {
      backtrack(curr + '(', left - 1, right)
    }
    if (right > left) {
      backtrack(curr + ')', left, right - 1)
    }
  }
  backtrack('', n, n)
  return result
}

console.log(generateParentheses(3))

Created 2022-02-26T17:29:14+00:00 · Edit