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;
}
相关推荐
XH华1 小时前
C语言第九章字符函数和字符串函数
c语言·开发语言
♞沉寂4 小时前
信号以及共享内存
linux·c语言·开发语言
1白天的黑夜14 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼354 小时前
力扣子集问题C++代码
c++·算法·leetcode
SunnyKriSmile4 小时前
【冒泡排序】
c语言·算法·排序算法
熬了夜的程序员4 小时前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
Miraitowa_cheems4 小时前
LeetCode算法日记 - Day 15: 和为 K 的子数组、和可被 K 整除的子数组
java·数据结构·算法·leetcode·职场和发展·哈希算法
_poplar_6 小时前
08.5【C++ 初阶】实现一个相对完整的日期类--附带源码
c语言·开发语言·数据结构·c++·vscode·算法·vim
意疏7 小时前
探秘C语言:数据在内存中的存储机制详解
c语言·开发语言