๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode][Medium][Stack] 22. Generate Parentheses ํžŒํŠธ, ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 11. 11. 22:59

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

 

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

 

ํžŒํŠธ 

https://www.youtube.com/watch?v=s9fokUqJ76A

์–ด๋–ป๊ฒŒ ํ’€์–ด์•ผ ํ•˜๋‚˜ 30๋ถ„ ์ •๋„ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€, ์œ„ ์˜์ƒ์„ ์ฐธ๊ณ ํ•ด์„œ ํžŒํŠธ๋ฅผ ์–ป์–ด์™”๋‹ค. 

๊ทœ์น™์€ close ๊ฐฏ์ˆ˜ < open ๊ฐฏ์ˆ˜ ์—ฌ์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ ! 

 

 

1์ฐจ ํ’€์ด 

๊ทธ ๊ทœ์น™์„ ์ฐธ๊ณ ํ•ด์„œ bfs๋กœ ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค. 

ํ•˜๋ฉด์„œ stack ์œ ํ˜•์œผ๋กœ neetcode์—์„œ ์ œ์‹œํ•œ ๋ฌธ์ œ์ง€๋งŒ dfs..๋กœ ์ ‘๊ทผํ•˜๋Š”๊ฒŒ ๋งž๋‚˜ ํ–ˆ์ง€๋งŒ, 

๊ทธ๋ž˜๋„ ํ‘ธ๋Š” ๊ฒƒ์— ์˜์˜๋ฅผ ๋‘๊ณ  ํ’€์—ˆ๋‹ค. 

class Solution(object):
    res = [] 
    
    def dfs(self, current, n):
        openCnt = current.count("(")
        closeCnt = current.count(")")
        
        if len(current) == 2 * n:
            if openCnt == n and closeCnt == n:
                self.res.append(current)
            return;
        else:            
            # close ๊ฐฏ์ˆ˜ < open ๊ฐฏ์ˆ˜ 
            if closeCnt <= openCnt:
                self.dfs(current + "(", n)
                self.dfs(current + ")", n)
    
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        self.res = [] # ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ „์— ์˜ˆ์ „์— ๋Œ๋ฆฐ ๊ฐ’ ์ดˆ๊ธฐํ™” 
        self.dfs("(", n)
        return self.res

 

 

ํ•ด์„ค

์œ„ ์˜์ƒ์—์„œ ์ œ์‹œํ•œ ํ’€์ด. 

stack์—๋‹ค๊ฐ€ ๋„ฃ๊ณ  backtrack์œผ๋กœ ํ•จ์ˆ˜๋ฅผ ๋Œ๋ฉด์„œ ํ‘ผ๋‹ค. 

 

 def generateParenthesis(self, n):
        # only add open paranthesis if open < n
        # only add a closing paranthesis if closed < open 
        # valid IIF open == closed == n 
        
        stack = [] 
        res = [] 
        
        def backtrack(openN, closedN):
            if openN == closedN == n:
                res.append("".join(stack))
                return 
            
            if openN < n:
                stack.append("(")
                backtrack(openN + 1, closedN)
                stack.pop() # clean up .. 
                
            if closedN < openN:
                stack.append(")")
                backtrack(openN, closedN + 1)
                stack.pop()
                
        backtrack(0,0)
        return res

 

 

 

 

 

๋ฐ˜์‘ํ˜•