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;
}
相关推荐
学习2年半11 分钟前
53. 最大子数组和
算法
君义_noip1 小时前
信息学奥赛一本通 1524:旅游航道
c++·算法·图论·信息学奥赛
烁3471 小时前
每日一题(小白)动态规划篇5
算法·动态规划
辰熤✔1 小时前
MQTT报文类型
c语言·网络
独好紫罗兰1 小时前
洛谷题单2-P5717 【深基3.习8】三角形分类-python-流程图重构
开发语言·python·算法
滴答滴答嗒嗒滴1 小时前
Python小练习系列 Vol.8:组合总和(回溯 + 剪枝 + 去重)
python·算法·剪枝
lidashent2 小时前
数据结构和算法——汉诺塔问题
数据结构·算法
小王努力学编程2 小时前
动态规划学习——背包问题
开发语言·c++·学习·算法·动态规划
f狐0狸x4 小时前
【蓝桥杯每日一题】4.1
c语言·c++·算法·蓝桥杯
ん贤4 小时前
2023第十四届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组(真题&题解)(C++/Java题解)
java·c语言·数据结构·c++·算法·蓝桥杯