1- def generate_parentheses_iterative (length : int ) -> list :
1+ def generate_parentheses_iterative (length : int ) -> list [ str ] :
22 """
33 Generate all valid combinations of parentheses (Iterative Approach).
44
55 The algorithm works as follows:
66 1. Initialize an empty list to store the combinations.
77 2. Initialize a stack to keep track of partial combinations.
8- 3. Start with empty string and push it onstack along with the counts of '(' and ')'.
8+ 3. Start with empty string and push it on stack along with the counts of '(' and ')'.
99 4. While the stack is not empty:
1010 a. Pop a partial combination and its open and close counts from the stack.
1111 b. If the combination length is equal to 2*length, add it to the result.
@@ -34,8 +34,11 @@ def generate_parentheses_iterative(length: int) -> list:
3434 >>> generate_parentheses_iterative(0)
3535 ['']
3636 """
37- result = []
38- stack = []
37+ if length == 0 :
38+ return ["" ]
39+
40+ result : list [str ] = []
41+ stack : list [tuple [str , int , int ]] = []
3942
4043 # Each element in stack is a tuple (current_combination, open_count, close_count)
4144 stack .append (("" , 0 , 0 ))
@@ -45,6 +48,7 @@ def generate_parentheses_iterative(length: int) -> list:
4548
4649 if len (current_combination ) == 2 * length :
4750 result .append (current_combination )
51+ continue
4852
4953 if open_count < length :
5054 stack .append ((current_combination + "(" , open_count + 1 , close_count ))
0 commit comments