|
| 1 | +""" |
| 2 | + Generate all valid combinations of parentheses (Iterative Approach). |
| 3 | +
|
| 4 | + The algorithm works as follows: |
| 5 | + 1. Initialize an empty list to store the combinations. |
| 6 | + 2. Initialize a stack to keep track of partial combinations. |
| 7 | + 3. Start with empty string and push it onstack along with the counts of '(' and ')'. |
| 8 | +
|
| 9 | + 4. While the stack is not empty: |
| 10 | + a. Pop a partial combination and its open and close counts from the stack. |
| 11 | + b. If the combination length is equal to 2*n, add it to the result. |
| 12 | + c. If open count is < n, push new combination with added '(' onto the stack. |
| 13 | + d. If close count < open count, push new combination with added ')' on stack. |
| 14 | + 5. Return the result containing all valid combinations. |
| 15 | +
|
| 16 | + Args: |
| 17 | + n (int): The desired length of the parentheses combinations. |
| 18 | +
|
| 19 | + Returns: |
| 20 | + list: A list of strings representing valid combinations of parentheses. |
| 21 | +
|
| 22 | + Time Complexity: |
| 23 | + O(2^(2n)). |
| 24 | +
|
| 25 | + Space Complexity: |
| 26 | + O(2^(2n)). |
| 27 | +""" |
| 28 | + |
| 29 | + |
| 30 | +def generate_parentheses(n: int) -> list: |
| 31 | + """ |
| 32 | + >>> generate_parentheses(3) |
| 33 | + ['()()()', '()(())', '(())()', '(()())', '((()))'] |
| 34 | +
|
| 35 | + >>> generate_parentheses(2) |
| 36 | + ['()()', '(())'] |
| 37 | +
|
| 38 | + >>> generate_parentheses(1) |
| 39 | + ['()'] |
| 40 | +
|
| 41 | + >>> generate_parentheses(0) |
| 42 | + [''] |
| 43 | +
|
| 44 | + """ |
| 45 | + result = [] |
| 46 | + stack = [] |
| 47 | + |
| 48 | + # Each element in stack has a tuple (current_combination, open_count, close_count). |
| 49 | + stack.append(("", 0, 0)) |
| 50 | + |
| 51 | + while stack: |
| 52 | + current_combination, open_count, close_count = stack.pop() |
| 53 | + |
| 54 | + if len(current_combination) == 2 * n: |
| 55 | + result.append(current_combination) |
| 56 | + else: |
| 57 | + if open_count < n: |
| 58 | + stack.append((current_combination + "(", open_count + 1, close_count)) |
| 59 | + if close_count < open_count: |
| 60 | + stack.append((current_combination + ")", open_count, close_count + 1)) |
| 61 | + |
| 62 | + return result |
| 63 | + |
| 64 | + |
| 65 | +def main() -> None: |
| 66 | + print(generate_parentheses(4)) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + import doctest |
| 71 | + |
| 72 | + doctest.testmod() |
| 73 | + main() |
0 commit comments