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 分钟前
算法奇妙屋(四十五)-CCPC备战之旅-1
java·开发语言·算法
无小道3 分钟前
算法——找规律
算法·规律
圣保罗的大教堂33 分钟前
leetcode 2069. 模拟行走机器人 II 中等
leetcode
地平线开发者39 分钟前
目标检测的 Anchor-Free 和 NMS 到底是什么?
算法·自动驾驶
北顾笙9801 小时前
day24-数据结构力扣
数据结构·算法·leetcode
网域小星球1 小时前
C语言从0入门(二十三)|预处理:#define、#include、条件编译详解
c语言·开发语言
水云桐程序员1 小时前
用C语言写LED灯嵌入式系统案例|STM32 LED控制与按键输入系统
c语言·stm32·单片机
智者知已应修善业1 小时前
【51单片机独立按键控制往复流水灯启停】2023-6-13
c++·经验分享·笔记·算法·51单片机
pen-ai1 小时前
MAD(Median Absolute Deviation)详解:最稳健的尺度估计方法
人工智能·算法
励志的小陈2 小时前
数据结构--队列(C语言实现)
c语言·开发语言·数据结构