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;
}
相关推荐
想跑步的小弱鸡1 分钟前
Leetcode hot 100(day 4)
算法·leetcode·职场和发展
Fantasydg3 分钟前
DAY 35 leetcode 202--哈希表.快乐数
算法·leetcode·散列表
jyyyx的算法博客3 分钟前
Leetcode 2337 -- 双指针 | 脑筋急转弯
算法·leetcode
SweetCode15 分钟前
裴蜀定理:整数解的奥秘
数据结构·python·线性代数·算法·机器学习
ゞ 正在缓冲99%…28 分钟前
leetcode76.最小覆盖子串
java·算法·leetcode·字符串·双指针·滑动窗口
xuanjiong29 分钟前
纯个人整理,蓝桥杯使用的算法模板day2(0-1背包问题),手打个人理解注释,超全面,且均已验证成功(附带详细手写“模拟流程图”,全网首个
算法·蓝桥杯·动态规划
小郝 小郝40 分钟前
【C语言】strstr查找字符串函数
c语言·开发语言
惊鸿.Jh1 小时前
【滑动窗口】3254. 长度为 K 的子数组的能量值 I
数据结构·算法·leetcode
明灯L1 小时前
《函数基础与内存机制深度剖析:从 return 语句到各类经典编程题详解》
经验分享·python·算法·链表·经典例题
碳基学AI1 小时前
哈尔滨工业大学DeepSeek公开课:探索大模型原理、技术与应用从GPT到DeepSeek|附视频与讲义免费下载方法
大数据·人工智能·python·gpt·算法·语言模型·集成学习