code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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