Objective
The objective of this program is to generate all valid combinations of n pairs of parentheses.
Valid combinations are those where each opening parenthesis ‘(‘ has a corresponding closing parenthesis ‘)’,
and the order is such that no closing parenthesis appears before its matching opening parenthesis.
Code
#include #include #include void generateParenthesisUtil(char *current, int pos, int open, int close, int n) { if (close == n) { printf("%s\n", current); return; } if (open < n) { current[pos] = '('; generateParenthesisUtil(current, pos + 1, open + 1, close, n); } if (close < open) { current[pos] = ')'; generateParenthesisUtil(current, pos + 1, open, close + 1, n); } } void generateParenthesis(int n) { char *current = (char *)malloc(2 * n + 1); current[2 * n] = '\0'; generateParenthesisUtil(current, 0, 0, 0, n); free(current); } int main() { int n; printf("Enter the number of pairs of parentheses: "); scanf("%d", &n); generateParenthesis(n); return 0; }
Program Structure
The program consists of the following main components:
- Function
generateParenthesisUtil
: This is a recursive function that builds valid combinations of parentheses. It takes the current combination string, its position, counts of open and close parentheses, and the total pairs n as parameters. - Function
generateParenthesis
: This function initializes the current combination string and calls the utility function. - Main Function: This is the entry point of the program where user input is taken for the number of pairs, and the generation function is invoked.
How to Run the Program
- Copy the code into a C compiler or IDE (e.g., GCC, Code::Blocks, Dev-C++).
- Compile the program to create the executable.
- Run the executable.
- When prompted, enter the number of pairs of parentheses you wish to generate.
- The program will output all valid combinations of the specified number of parentheses.
Example
If you enter 3, the output will be:
((())) (()()) (())() ()(()) ()()()