Program Code
def generate_parentheses(n):
"""
Generate all valid combinations of n pairs of parentheses.
Parameters:
n (int): The number of pairs of parentheses.
Returns:
List[str]: A list containing all valid combinations of n pairs of parentheses.
"""
def backtrack(current, open_count, close_count):
# If the current combination is of the maximum length
if len(current) == 2 * n:
result.append(current)
return
# Add an open parenthesis if we still have open parentheses left to add
if open_count < n:
backtrack(current + '(', open_count + 1, close_count)
# Add a close parenthesis if we have open parentheses that can be closed
if close_count < open_count:
backtrack(current + ')', open_count, close_count + 1)
result = []
backtrack('', 0, 0)
return result
# Example usage:
if __name__ == "__main__":
n = 3 # You can change this value to generate different numbers of pairs
combinations = generate_parentheses(n)
print("Valid combinations of", n, "pairs of parentheses:", combinations)
Program Structure Explanation
This Python program consists of a main function generate_parentheses(n)
and a nested helper function backtrack(current, open_count, close_count)
. Here’s how the program works:
- Function Definition:
- The
generate_parentheses
function takes an integern
as input, representing the number of pairs of parentheses. - It initializes an empty list
result
to store valid combinations.
- The
- Backtracking Algorithm:
- The
backtrack
function is a recursive function responsible for building the combinations. - It takes the current string of parentheses, the count of open parentheses, and the count of close parentheses as parameters.
- If the current combination reaches a length of
2 * n
, it means we have a valid combination, which is added toresult
. - The function explores two main choices:
- Add an open parenthesis if we still have open parentheses left to add (
open_count < n
). - Add a close parenthesis if we have an open parenthesis that can be closed (
close_count < open_count
).
- Add an open parenthesis if we still have open parentheses left to add (
- The
- Execution:
- The
if __name__ == "__main__"
block allows for testing the function by specifying a value forn
and printing the resulting combinations.
- The
How to Run the Program
To run this program, copy the code into a Python environment or a script file and execute it. Modify the value of n
to generate different numbers of parentheses pairs. The result will be printed to the console.