backtracking.generate_parentheses_iterative¶
Functions¶
|
Generate all valid combinations of parentheses (Iterative Approach). |
Module Contents¶
- backtracking.generate_parentheses_iterative.generate_parentheses_iterative(length: int) list[str]¶
Generate all valid combinations of parentheses (Iterative Approach).
The algorithm works as follows: 1. Initialize an empty list to store the combinations. 2. Initialize a stack to keep track of partial combinations. 3. Start with empty string and push it on stack along with
the counts of ‘(’ and ‘)’.
- While the stack is not empty:
Pop a partial combination and its open and close counts from the stack.
If the combination length is equal to 2*length, add it to the result.
If open count < length, push new combination with added ‘(’ on stack.
If close count < open count, push new combination with added ‘)’ on stack.
Return the result containing all valid combinations.
- Args:
length: The desired length of the parentheses combinations
- Returns:
A list of strings representing valid combinations of parentheses
- Time Complexity:
O(2^(2*length))
- Space Complexity:
O(2^(2*length))
>>> generate_parentheses_iterative(3) ['()()()', '()(())', '(())()', '(()())', '((()))'] >>> generate_parentheses_iterative(2) ['()()', '(())'] >>> generate_parentheses_iterative(1) ['()'] >>> generate_parentheses_iterative(0) ['']