From 02736c024353102e45950aed323a9794c33e0515 Mon Sep 17 00:00:00 2001 From: Saurabh Agrawal <64404786+saurabhagrawal1998@users.noreply.github.com> Date: Sun, 1 Oct 2023 00:02:22 +0530 Subject: [PATCH] added the code for problem generate-parenthesis.c --- leetcode/src/generate-parenthesis.c | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 leetcode/src/generate-parenthesis.c diff --git a/leetcode/src/generate-parenthesis.c b/leetcode/src/generate-parenthesis.c new file mode 100644 index 00000000..7e28cd6c --- /dev/null +++ b/leetcode/src/generate-parenthesis.c @@ -0,0 +1,46 @@ +// Problem Link: https://leetcode.com/problems/generate-parentheses/ +// Title: 22. Generate Parentheses + +// This C program generates all valid combinations of n pairs of parentheses. +// It uses a recursive approach with backtracking to explore and construct valid combinations. + + +#include +#include +#include + +void generateParenthesisRecursive(char **result, int *returnSize, char *current, int open, int close, int n) { + if (strlen(current) == 2 * n) { + result[(*returnSize)] = strdup(current); + (*returnSize)++; + return; + } + + if (open < n) { + current[strlen(current)] = '('; + generateParenthesisRecursive(result, returnSize, current, open + 1, close, n); + current[strlen(current) - 1] = '\0'; // Backtrack + } + + if (close < open) { + current[strlen(current)] = ')'; + generateParenthesisRecursive(result, returnSize, current, open, close + 1, n); + current[strlen(current) - 1] = '\0'; // Backtrack + } +} + +char **generateParenthesis(int n, int *returnSize) { + int maxCombinations = 10000; // Maximum number of combinations + char **result = (char **)malloc(maxCombinations * sizeof(char *)); + *returnSize = 0; + + char *current = (char *)malloc(2 * n + 1); // Allocate enough memory for the parentheses and null terminator + memset(current, 0, 2 * n + 1); + + generateParenthesisRecursive(result, returnSize, current, 0, 0, n); + + free(current); + + return result; +} +