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;
}
相关推荐
来荔枝一大筐12 分钟前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
apocelipes35 分钟前
POSIX兼容系统上read和write系统调用的行为总结
linux·c语言·c++·python·golang·linux编程
暴风鱼划水1 小时前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
zl_vslam1 小时前
SLAM中的非线性优-3D图优化之轴角在Opencv-PNP中的应用(一)
前端·人工智能·算法·计算机视觉·slam se2 非线性优化
是苏浙1 小时前
零基础入门C语言之C语言实现数据结构之顺序表应用
c语言·数据结构·算法
lkbhua莱克瓦242 小时前
Java基础——常用算法3
java·数据结构·笔记·算法·github·排序算法·学习方法
小白程序员成长日记2 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白2 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
小猪咪piggy2 小时前
【算法】day16 动态规划
算法·动态规划
ohnoooo92 小时前
251106 算法
数据结构·c++·算法