-
Leetcode 22. Generate Parentheses개발/Leetcode 2023. 7. 1. 10:36
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 = []
q = ["()" * n]
while q:p = q.pop()if p not in answer:answer.append(p)q += self.findAndReplace(p)
return answer
def findAndReplace(self, s: str) -> list[str]:result = []prev_index = 0for i in range(s.count(')(')):j = s.index(')(', prev_index + 1)prev_index = jresult.append(s[:j] + '()' + s[j + 2:])
return result
DFS로도 풀 수 있었겠지만, string 메소드를 공부해야해 위와 같이 코드를 작성함
'개발 > Leetcode' 카테고리의 다른 글
Leetcode 2011. Final Value of Variable After Performing Operations (0) 2023.07.02 Leetcode 43. Multiply Strings (0) 2023.07.01 Leetcode 2744. Find Maximum Number of String Pairs (0) 2023.07.01 Leetcode 2305. Fair Distribution of Cookies (0) 2023.07.01 Leetcode 1970. Last Day Where You Can Still Cross (0) 2023.06.30