컴퓨터공학/LeetCode 1000

[LeetCode] 22. Generate Parentheses

saurus2 2022. 10. 26. 04:03

22. Generate Parentheses

Medium

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

문제 풀이

괄호들의 조합을 만들어내는 문제이다.

이 문제에서 원하는 괄호의 배치는 잘 형성되어있는 괄호이다. 

즉, 열린 괄호와 닫힌 괄호가 알맞게 조합되어있어야한다. 

예를 들어 "(())" 는 가능하지만 ")()(" 는 안된다.

백트레킹

  • 이진트리를 백트레킹하여 구현한다고 생각하자.
  • 자식은 '(' 와 ')' 두개 이기 때문에 이진트리이며, 열린 괄호와 닫힌 괄호의 갯수를 세어가며 재귀호출을 한다.
  • 그 이유는, 열린 괄호보다 닫히는 괄호가 많다면 제대로 만들어진 괄호 배열을 만들 수 없다.
  • 그래서 먼저 열린괄호가 선택되야하며 항상 닫히는 괄호가 선택될때, 열린괄호 갯수가 더 많은 상태에서 선택되어야한다.
  • 그리고 각 괄호의 갯수가 n개가 되면 정답을 리스트에 넣는다. 

소스 코드

백트레킹

Time Complexity: O(4^n / root(n))

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        # exception
        if n == 1:
            return ["()"]
        # making parentheses set
        res = []
        def dfs(cnt1, cnt2, temp):
            if cnt1 == n and cnt2 == n:
                res.append(temp)
                return
            
            if cnt1 < n:
                dfs(cnt1 + 1, cnt2, temp + '(')
            if cnt2 < n and cnt1 > cnt2:
                dfs(cnt1, cnt2 + 1, temp + ')')
        dfs(0, 0, '')
        return res