[Leetcode] 22. Generate Parentheses

Seongjun Lee·2022년 2월 19일
0

[Leetcode] - Problem

목록 보기
22/43
post-thumbnail

Problem

문제 링크

숫자 n이 주어질때, 괄호 (,)n개의 쌍이맞는 올바른 괄호가 될 수 있는 경우를 모두 만들어라.

Solution

  1. 재귀함수를 이용한 방법
  2. 주어진 N보다 열린괄호가 적으면 열린괄호를 추가하는 함수 호출과 열린괄호보다 닫힌괄호의 수가 적으면 닫힌괄호를 추가하는 로직을 수행
  3. 재귀함수가 깊어질때 N보다 열린괄호와 닫힌괄호의 수가 커지지 않도록 조건 처리
  4. 열린괄호와 닫힌괄호와 N의 값이 같을때 현재 상태의 문자열을 저장한다.

JS CODE

/**
 * @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
}
profile
Hi there 👋

0개의 댓글