Generate Parentheses

Key Idea

Solution

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        output_list = []

        def backtrack(current_string, open_count, close_count):
            # Stop when the string has length 2n
            if len(current_string) == 2 * n:
                output_list.append(current_string)
                return

            # Add "(" if we still have opening brackets left
            if open_count < n:
                backtrack(
                    current_string + "(",
                    open_count + 1,
                    close_count
                )

            # Add ")" only if it will not break validity
            if close_count < open_count:
                backtrack(
                    current_string + ")",
                    open_count,
                    close_count + 1
                )

        backtrack("", 0, 0)

        return output_list

Complexity