Zero to Hero
article thumbnail
Published 2021. 4. 5. 13:30
22. Generate Parentheses Algorithm
 

Generate Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1. Brute Force (특정 길이의 괄호 문자열을 전부 만들고 적합한지 판단)

from typing import *


class Solution:
    answer = []

    def generateParenthesis(self, n: int) -> List[str]:
        self.answer=[]
        self.dfs("", n)
        return self.answer
    def dfs(self, cur, target):
        if len(cur) == target * 2:
            if self.check(cur):
                self.answer.append(cur)
            return
        else:
            self.dfs(cur + "(", target)
            self.dfs(cur + ")", target)

    def check(self, input_str):
        stack = []
        for i in range(len(input_str)):
            if not stack or input_str[i] == "(":
                stack.append(input_str[i])
            else:
                if not stack or stack[-1] != "(":
                    return False
                else:
                    stack.pop()
        if not stack:
            return True
        return False

2. 창의적인 Backtracking

from typing import *


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

        def dfs(string_list, left, right):
            if len(string_list) == 2 * n:
                answer.append("".join(string_list))
                return

            if left < n:
                string_list.append("(")
                dfs(string_list, left + 1, right)
                string_list.pop()
            if right < left:
                string_list.append(")")
                dfs(string_list, left, right + 1)
                string_list.pop()

        dfs([], 0, 0)
        return answer

 

'Algorithm' 카테고리의 다른 글

46. Permutations  (0) 2021.04.05
94. Binary Tree Inorder Traversal  (0) 2021.04.05
2105. [모의 SW 역량테스트] 디저트 카페  (0) 2021.04.04
15. 3Sum  (0) 2021.04.02
5. Longest Palindromic Substring  (0) 2021.04.01
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!