22 generate parentheses

#define SIZE 10000

void addParenthesisRecursively(int left, int right, char* str, char**result, int* returnSize, int n) {
    if((left == 0) && (right == 0))
        result[(*returnSize)++] = str;
    else {
        char* newStr = (char *)malloc(sizeof(char) * (2*n+1));
        if(left > 0) {
            strcpy(newStr, str);
            addParenthesisRecursively(left-1, right+1, strcat(newStr, "("), result, returnSize, n);
        }
        if(right > 0) {
            strcpy(newStr, str);
            addParenthesisRecursively(left, right-1, strcat(newStr, ")"), result, returnSize, n);
        }
    }
}

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** generateParenthesis(int n, int* returnSize) {
    char** result = (char **)malloc(sizeof(char *) * SIZE);
    addParenthesisRecursively(n, 0, "", result, returnSize, n);
    return result;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容