[LeetCode]Generate Parentheses

2023. 4. 12. 22:10·SW개발/코딩테스트

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

 

Generate Parentheses - LeetCode

Can you solve this real interview question? Generate Parentheses - Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.   Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Exa

leetcode.com

 

문제 분석

주어진 n개의 괄호를 가지고 가능한 괄호의 조합을 모두 구하는 문제입니다.

 

처음 시도한 답안

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        answer = []

        def dfs(char, remaining_open_braket, remaining_close_braket, answer):
            # 모든 괄호가 사용되면 정답에 추가함.
            if len(char) == 2 * n:
                answer.append(char)
                return 

            # 열려있는 괄호가 사용 가능할 때만 추가, 열린 괄호부터 사용
            if remaining_open_braket > 0:
                dfs(char + '(', remaining_open_braket-1, remaining_close_braket, answer)
            
            # 남은 닫혀있는 괄호의 갯수가 더 많을때만 괄호를 닫을 수 있음.
            if remaining_open_braket < remaining_close_braket:
                dfs(char + ')', remaining_open_braket, remaining_close_braket-1, answer)

        dfs('', n, n, answer)

        return answer

접근 방법

  1. dfs를 통해 재귀 방식으로 괄호쌍을 만들어 나간다.
  2. 만약 만들어진 글자가 n*2 라면 (모든 괄호가 사용되면) 정답에 추가한다.
  3. 열린 괄호가 사용가능한 경우에는 ( 를 추가한다.
    1. 재귀 호출을 통해 남아있는 열린 괄호의 수를 한개 감소하고, ( 문자를 추가한다.
  4. 남아있는 닫힌 괄호의 수가 남아있는 열린 괄호의 수보다 많을때만 ) 를 추가한다.
    닫힌 괄호가 더 많이 사용된다면 valid한 parentheses가 되지 않기 때문이다.
    1. 재귀 호출을 통해 남아있는 닫힌 괄호의 수를 한개 감소하고, ) 문자를 추가한다.

dfs 탐색을 통해서 parentheses를 만드는 방법입니다. 다음의 조건들을 만족해야 올바른 괄호를 만들 수 있습니다.

  • 가장 처음에는 열린 괄호부터 사용해야 합니다.
  • 닫힌 괄호의 수는 항상 열린 괄호의 수보다 적거나 같아야 합니다.
  • 재귀적으로 호출하면서 모든 괄호가 사용되면 정답에 추가합니다. (혹은, 남아있는 열린, 닫힌 괄호의 수가 모두 0일 때)

( ) 두개의 괄호를 가지고 이진 트리의 형태로 괄호쌍을 그려나가다 보면 dfs 탐색으로 해결할 수 있다는 힌트를 얻을 수 있습니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Best Time to Buy and Sell Stock  (0) 2023.04.30
[LeetCode]Swap Nodes in Pairs  (0) 2023.04.13
[LeetCode]Remove Nth Node From End of List  (0) 2023.04.11
[LeetCode]Letter Combinations of a Phone Number  (0) 2023.04.10
[LeetCode]3Sum  (0) 2023.04.09
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Best Time to Buy and Sell Stock
  • [LeetCode]Swap Nodes in Pairs
  • [LeetCode]Remove Nth Node From End of List
  • [LeetCode]Letter Combinations of a Phone Number
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    배달
    어플리케이션
    배달비 공유
    플레이스토어
    Contributor
    트리 #AVL #알고리즘 #자료구조
    g
    라이프 스타일
    음식
    컨트리뷰터
    django
    오픈소스
    배공파용
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Generate Parentheses
상단으로

티스토리툴바