LeetCode Generate Parentheses (JavaScript)

2025. 11. 17. 20:51·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/generate-parentheses/description/

문제 설명

더보기
더보기

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Constraints:

  • 1 <= n <= 8

문제 풀이

dfs를 활용해 문제 해결

dfs의 인자로 빈문자열, n(개의 여는괄호), n(개의 닫는괄호) 를 전달 받음

1. left가 0이라는 건 여는 괄호를 모두 사용했으므로 answer에 만들어진 괄호 형태 저장 (right는 남아있을 수 있으므로 right가 0보다 크다면 ')'를 붙여줌)

2. left가 0이 아니라면 str에 '('를 붙여주고 left - 1로 재귀

3. right가 0이 아니라면 str에 ')'를 붙여주고 right -1로 재귀. 단, 올바른 괄호를 만들기 위해 right - 1를 한 값이 left보다 크거나 같아야함 (left보다 작다면 올바르지 않은 괄호 형태임)

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

    const dfs = (str, left, right) => {
        if (left === 0) {
            return answer.push(str + ')'.repeat(right));
        }

        if (left !== 0) {
            dfs(str + "(", left - 1, right);
        }

        if (right !== 0 && left <= right - 1) {
            dfs(str + ")", left, right - 1);
        }
    }

    dfs('', n, n);

    return answer;
};

결론

stack자료구조, dfs알고리즘을 이용하여 풀이

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Swap Nodes in Pairs (JavaScript)  (0) 2025.11.19
LeetCode Word Search (JavaScript), DFS  (0) 2025.11.18
LeetCode Remove Nth Node From End of List (JavaScript)  (0) 2025.11.17
LeetCode 4Sum (JavaScript)  (0) 2025.11.17
LeetCode Letter Combinations of a Phone Number (JavaScript)  (0) 2025.11.17
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Swap Nodes in Pairs (JavaScript)
  • LeetCode Word Search (JavaScript), DFS
  • LeetCode Remove Nth Node From End of List (JavaScript)
  • LeetCode 4Sum (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (212) N
      • 프론트엔드 (64) N
        • JavaScript (51)
        • HTML (3)
        • React (7) N
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (126) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (37) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Generate Parentheses (JavaScript)
상단으로

티스토리툴바