LeetCode //C - 22. Generate Parentheses

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: "((()))","(()())","(())()","()(())","()()()"

Example 2:

Input: n = 1
Output: "()"

Constraints:
  • 1 <= n <= 8

From: LeetCode

Link: 22. Generate Parentheses


Solution:

Ideas:

The recursive approach is employed to generate all possible combinations. At each recursive call, the code decides whether to add an opening parenthesis ( or a closing parenthesis ) based on certain conditions.

Key Observations:

You can only add an opening parenthesis if the number used so far is less than n.

You can only add a closing parenthesis if the number of opening parentheses used so far is greater than the number of closing parentheses. This ensures that we never have a situation like ()).

Code:
c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void generate(int n, int open, int close, char* current, int index, char*** result, int* returnSize) {
    if (index == 2 * n) {
        current[index] = '\0';
        (*result)[*returnSize] = strdup(current);
        (*returnSize)++;
        return;
    }
    
    if (open < n) {
        current[index] = '(';
        generate(n, open + 1, close, current, index + 1, result, returnSize);
    }
    
    if (close < open) {
        current[index] = ')';
        generate(n, open, close + 1, current, index + 1, result, returnSize);
    }
}

int catalan(int n) {
    int result = 1;
    for (int i = 0; i < n; ++i) {
        result *= (2 * n - i);
        result /= (i + 1);
    }
    return result / (n + 1);
}

char** generateParenthesis(int n, int* returnSize) {
    *returnSize = 0;
    int maxCombination = catalan(n);
    char** result = (char**) malloc(maxCombination * sizeof(char*));
    char* current = (char*) malloc(2 * n + 1);
    
    generate(n, 0, 0, current, 0, &result, returnSize);
    
    free(current);
    return result;
}
相关推荐
Interview Aid11232 分钟前
Stripe VO 面经汇总:5 轮面试题目与考察重点
算法
EEET智选37 分钟前
科技晨间速报 | AI 安全警钟、开源新模型与苹果智能家居
人工智能·科技·算法·机器学习·ai
挖掘狂人1 小时前
哈希算法:一根看不见的 "指纹",如何撑起整个互联网
算法·程序员·掘金技术征文
鶴哥只手遮天1 小时前
ecRad 1.5.0 算法原理详解
算法·开源
老王爱玩车1 小时前
预处理详解
c语言·开发语言·学习
不会就选b1 小时前
算法日常・每日刷题--<动态规划>22
算法·动态规划
释厄6231 小时前
字画同体论——字即画·几何即字·漫画与小说=文本层
人工智能·算法
学逆向的2 小时前
C 控制台指令
c语言·开发语言·网络安全
沫璃染墨2 小时前
从零入门数据结构与算法(一):复杂度分析——从算法效率到时间与空间复杂度
c语言·开发语言·数据结构·笔记·算法·飞书
想做小南娘,发现自己是女生喵2 小时前
第三周学习文档 Linux C 多进程与多线程
linux·c语言·学习