Generate valid combinations of balanced parentheses for a given n. :param n: An integer representing the number of pairs of parentheses. :return: A list of strings with valid combinations. This function uses a recursive approach to generate the combinations. Time Complexity:
(n: int)
| 46 | |
| 47 | |
| 48 | def generate_parenthesis(n: int) -> list[str]: |
| 49 | """ |
| 50 | Generate valid combinations of balanced parentheses for a given n. |
| 51 | |
| 52 | :param n: An integer representing the number of pairs of parentheses. |
| 53 | :return: A list of strings with valid combinations. |
| 54 | |
| 55 | This function uses a recursive approach to generate the combinations. |
| 56 | |
| 57 | Time Complexity: O(2^(2n)) - In the worst case, we have 2^(2n) combinations. |
| 58 | Space Complexity: O(n) - where 'n' is the number of pairs. |
| 59 | |
| 60 | Example 1: |
| 61 | >>> generate_parenthesis(3) |
| 62 | ['((()))', '(()())', '(())()', '()(())', '()()()'] |
| 63 | |
| 64 | Example 2: |
| 65 | >>> generate_parenthesis(1) |
| 66 | ['()'] |
| 67 | |
| 68 | Example 3: |
| 69 | >>> generate_parenthesis(0) |
| 70 | [''] |
| 71 | """ |
| 72 | |
| 73 | result: list[str] = [] |
| 74 | backtrack("", 0, 0, n, result) |
| 75 | return result |
| 76 | |
| 77 | |
| 78 | if __name__ == "__main__": |
nothing calls this directly
no test coverage detected