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;
}
相关推荐
_Narcissus_11 分钟前
分治&递归
数据结构·c++·笔记·算法·leetcode·递归·分治
明志数科13 分钟前
具身智能数据工程全链路解析:从真实产线采集到LeRobot适配
网络·人工智能·算法
小O的算法实验室22 分钟前
AAAI-26,Lehmer编码搜索排列空间的理论与实证分析
算法
lch2011_yb24 分钟前
CSP-S 2023 密码锁 题解
算法
OPEN-F1 小时前
C++进阶教程:运算符重载与类型转换
java·c++·算法
牧杉-惊蛰2 小时前
将数组对象根据自定义排列
java·开发语言·算法
inquisiter2 小时前
损失函数在标量和矩阵上的求导对比
线性代数·算法·矩阵
离凌寒2 小时前
一、关于st上制作外部烧录算法时软件识别不到算法文件的问题总结
算法
v_for_van2 小时前
C语言__attribute__
服务器·c语言·开发语言·mcu·嵌入式·嵌入式实时数据库