Skip to content

22. 括号生成

22. 括号生成

代码

javascript
// 22. 括号生成:https://leetcode.cn/problems/generate-parentheses/description/
// 输入:n = 3
// 输出:["((()))","(()())","(())()","()(())","()()()"]

export function generateParenthesis (n) {
  let resSet = new Set([''])
  for (let i = 1; i <= n; i++) {
    const newSet = new Set()
    for (let item of resSet.values()) {
      for (let j = 0; j <= item.length; j++) {
        newSet.add(`${item.slice(0, j)}()${item.slice(j)}`)
      }
    }
    resSet = newSet
  }
  return [...resSet]
}
typescript
// 22. 括号生成:https://leetcode.cn/problems/generate-parentheses/description/
// 输入:n = 3
// 输出:["((()))","(()())","(())()","()(())","()()()"]

export function generateParenthesis (n: number): string[] {
  let resSet = new Set<string>([''])
  for (let i = 1; i <= n; i++) {
    const newSet = new Set<string>()
    for (let item of resSet.values()) {
      for (let j = 0; j <= item.length; j++) {
        newSet.add(`${item.slice(0, j)}()${item.slice(j)}`)
      }
    }
    resSet = newSet
  }
  return [...resSet]
}

测试代码

ts
import { expect, test } from 'vitest'
import { generateParenthesis } from './typescript.ts'
import { generateParenthesis as generateParenthesisJs } from './javascript.js'

test(`generateParenthesis`, () => {
  expect(generateParenthesis(3)).toEqual(['()()()', '(())()', '()(())', '(()())', '((()))'])
})

test(`generateParenthesisJs`, () => {
  expect(generateParenthesisJs(2)).toEqual(['()()', '(())'])
})