C语言 | Leetcode C语言题解之第22题括号生成

题目:

题解:

cpp 复制代码
// 回溯法求解
#define MAX_SIZE 1430  // 卡特兰数: 1, 1, 2, 5, 14, 42, 132, 429, 1430
void generate(int left, int right, int n, char *str, int index, char **result, int *returnSize) {
    if (index == 2 * n) { // 当前长度已达2n
        result[(*returnSize)] =  (char*)calloc((2 * n + 1), sizeof(char));
        strcpy(result[(*returnSize)++], str);
        return;
    }
    // 如果左括号数量不大于 n,可以放一个左括号
    if (left < n) {
        str[index] = '(';
        generate(left + 1, right, n, str, index + 1, result, returnSize);
    }
    // 如果右括号数量小于左括号的数量,可以放一个右括号
    if (right < left) {
        str[index] = ')';
        generate(left, right + 1, n, str, index + 1, result, returnSize);
    }
}
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** generateParenthesis(int n, int *returnSize) {
    char *str = (char*)calloc((2 * n + 1), sizeof(char));
    char **result = (char **)malloc(sizeof(char *) * MAX_SIZE);
    *returnSize = 0;
    generate(0, 0, n, str, 0, result, returnSize);
    return result;
}
相关推荐
RuoZoe11 小时前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_4 天前
C语言内存函数
c语言·后端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll5 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐5 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶6 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode