프로그래밍
leecode 22. Generate Parentheses 풀이
웃즐
2021. 4. 23. 19:37
문제 :
아래와 같이 n이 주어질 때 ( 1 <= n <= 8 ) 가능한 parentheses를 모두 반환하라
Example 1:Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1 Output: ["()"]
Follow up :
아이디어 : 처음에 '(' 를 path에 설정하여 ')' 갯수가 '(' 를 넘지 않도록 증가시키며 generate한다. 재귀를 통해 path를 생성하여 ans에 반환한다.
코드 :
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
global ans
ans = []
self.find(1, 0, '(', n)
return ans
def find(self, l, r, path, n):
global ans
if l == r and l == n:
ans.append(path)
return
if l < r or n < l:
return
elif l == r:
return self.find(l+1, r, path + '(', n)
else:
self.find(l, r+1, path + ')', n)
self.find(l+1, r, path + '(', n)
return