Python
Python

 

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 integer n as input, representing the number of pairs of parentheses.
    • It initializes an empty list result to store valid combinations.
  • 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 to result.
    • 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).
  • Execution:
    • The if __name__ == "__main__" block allows for testing the function by specifying a value for n and printing the resulting combinations.

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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)