Skip to content

[Leetcode] 22. Generate Parentheses โ€‹

#์กฐํ•ฉ

Problem โ€‹

๋ฌธ์ œ ๋งํฌ

์ˆซ์ž n์ด ์ฃผ์–ด์งˆ๋•Œ, ๊ด„ํ˜ธ (,)๋ฅผ n๊ฐœ์˜ ์Œ์ด๋งž๋Š” ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ๊ฐ€ ๋  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ๋ชจ๋‘ ๋งŒ๋“ค์–ด๋ผ.

Solution โ€‹

  1. ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•œ ๋ฐฉ๋ฒ•
  2. ์ฃผ์–ด์ง„ N๋ณด๋‹ค ์—ด๋ฆฐ๊ด„ํ˜ธ๊ฐ€ ์ ์œผ๋ฉด ์—ด๋ฆฐ๊ด„ํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ํ•จ์ˆ˜ ํ˜ธ์ถœ๊ณผ ์—ด๋ฆฐ๊ด„ํ˜ธ๋ณด๋‹ค ๋‹ซํžŒ๊ด„ํ˜ธ์˜ ์ˆ˜๊ฐ€ ์ ์œผ๋ฉด ๋‹ซํžŒ๊ด„ํ˜ธ๋ฅผ ์ถ”๊ฐ€ํ•˜๋Š” ๋กœ์ง์„ ์ˆ˜ํ–‰
  3. ์žฌ๊ท€ํ•จ์ˆ˜๊ฐ€ ๊นŠ์–ด์งˆ๋•Œ N๋ณด๋‹ค ์—ด๋ฆฐ๊ด„ํ˜ธ์™€ ๋‹ซํžŒ๊ด„ํ˜ธ์˜ ์ˆ˜๊ฐ€ ์ปค์ง€์ง€ ์•Š๋„๋ก ์กฐ๊ฑด ์ฒ˜๋ฆฌ
  4. ์—ด๋ฆฐ๊ด„ํ˜ธ์™€ ๋‹ซํžŒ๊ด„ํ˜ธ์™€ N์˜ ๊ฐ’์ด ๊ฐ™์„๋•Œ ํ˜„์žฌ ์ƒํƒœ์˜ ๋ฌธ์ž์—ด์„ ์ €์žฅํ•œ๋‹ค.

JS CODE โ€‹

javascript
/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function (n) {
  let answer = []

  const combination = (openCnt, closeCnt, str) => {
    if (n < openCnt || n < closeCnt) return
    if (n === openCnt && n === closeCnt) {
      answer.push(str)
    }

    if (openCnt < n) combination(openCnt + 1, closeCnt, str + '(')
    if (closeCnt < openCnt) combination(openCnt, closeCnt + 1, str + ')')
  }

  combination(0, 0, '')

  return answer
}