개발/Leetcode
Leetcode 22. Generate Parentheses
지산동고라니
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 = 0
for i in range(s.count(')(')):
j = s.index(')(', prev_index + 1)
prev_index = j
result.append(s[:j] + '()' + s[j + 2:])
return result
DFS로도 풀 수 있었겠지만, string 메소드를 공부해야해 위와 같이 코드를 작성함