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;
}
相关推荐
闪电麦坤95几秒前
数据结构:递归的种类(Types of Recursion)
数据结构·算法
Gyoku Mint44 分钟前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
纪元A梦1 小时前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法
px不是xp1 小时前
山东大学算法设计与分析复习笔记
笔记·算法·贪心算法·动态规划·图搜索算法
枫景Maple2 小时前
LeetCode 2297. 跳跃游戏 VIII(中等)
算法·leetcode
鑫鑫向栄2 小时前
[蓝桥杯]修改数组
数据结构·c++·算法·蓝桥杯·动态规划
鑫鑫向栄2 小时前
[蓝桥杯]带分数
数据结构·c++·算法·职场和发展·蓝桥杯
小wanga3 小时前
【递归、搜索与回溯】专题三 穷举vs暴搜vs回溯vs剪枝
c++·算法·机器学习·剪枝
天宫风子3 小时前
线性代数小述(一)
线性代数·算法·矩阵·抽象代数