5/09/2020

[LeetCode] 22. Generate Parentheses

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

Recursively add open bracket and close bracket for valid sequence.



class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        def helper(left, right, tmp):
            if left == right == n:
                yield "".join(tmp)
            else:
                if left < n:
                    tmp.append("(")
                    yield from helper(left + 1, right, tmp)
                    tmp.pop()
                
                if left > right:
                    tmp.append(")")
                    yield from helper(left, right + 1, tmp)
                    tmp.pop()
        
        return list(helper(0, 0, []))

Edited on 06/16/2021. Refactor by using 'yield'.

No comments:

Post a Comment