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;
}
相关推荐
浅陌pa7 分钟前
01:(寄存器开发)点亮一个LED灯
c语言·stm32·单片机·嵌入式硬件
武昌库里写JAVA31 分钟前
Vue3常用API总结
数据结构·spring boot·算法·bootstrap·课程设计
C++忠实粉丝33 分钟前
位运算(7)_消失的两个数字
算法
卑微求AC33 分钟前
(C语言贪吃蛇)4.贪吃蛇地图优化及算法说明
c语言·算法
sjsjs1134 分钟前
【动态规划-最长公共子序列(LCS)】【hard】力扣1458. 两个子序列的最大点积
算法·leetcode·动态规划
qq_5352461435 分钟前
代码随想录 101. 孤岛的总面积
算法·深度优先·图论
sjsjs1135 分钟前
【动态规划-最长公共子序列(LCS)】力扣583. 两个字符串的删除操作
算法·leetcode·动态规划
陈序缘38 分钟前
LeetCode讲解篇之79. 单词搜索
算法·leetcode·职场和发展
南石.1 小时前
JVM 基础、GC 算法与 JProfiler 监控工具详解
jvm·算法
DdddJMs__1351 小时前
C语言 | Leetcode C语言题解之第458题可怜的小猪
c语言·leetcode·题解