#include <stdio.h> #include <stdlib.h> /** * 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 = NULL; if(n == 1) { /* if n == 1 */ result = (char **) malloc(sizeof(char *) * 1); result[0] = (char *) malloc(sizeof(char) * 2 * n); result[0][0] = '('; result[0][1] = ')'; *returnSize = 1; } else { /* if n > 1 */ int subSize = 0; char ** subResult = generateParenthesis(n-1, &subSize); *returnSize = subSize * 3 - 1; printf("returnSize = %d ", *returnSize); result = (char **) malloc(sizeof(char *) * (*returnSize)); int i=0,j=0; for(i=0; i<subSize; i++) { result[i] = (char *) malloc(sizeof(char) * 2 * n); result[i][0] = '('; result[i][2*n-1] = ')'; for(j=0; j<2*(n-1); j++) { result[i][j+1] = subResult[i][j]; } } int m = subSize; for(i=0; i<subSize-1; i++) { result[i+m] = (char *) malloc(sizeof(char) * 2 * n); result[i+m][2*n-2] = '('; result[i+m][2*n-1] = ')'; for(j=0; j<2*(n-1); j++) { result[i+m][j] = subResult[i][j]; } } m = subSize + subSize - 1; for(i=0; i<subSize-1; i++) { result[i+m] = (char *) malloc(sizeof(char) * 2 *n); result[i+m][0] = '('; result[i+m][1] = ')'; for(j=0; j<2*(n-1); j++) { result[i+m][j+2] = subResult[i][j]; } } result[*returnSize-1] = (char *) malloc(sizeof(char) * 2 * n); result[*returnSize-1][0] = '('; result[*returnSize-1][1] = ')'; for(j=0; j<2*(n-1); j++) { result[*returnSize-1][j+2] = subResult[i][j]; } for(i=0; i<subSize; i++) { free(subResult[i]); } free(subResult); } char ** append = (char **) malloc(sizeof(char *) * (*returnSize)); int k=0,j=0; for(k=0; k<(*returnSize); k++) { append[k] = (char *) malloc(sizeof(char) * (2 * n+1)); for(j=0; j< 2*n; j++) { append[k][j] = result[k][j]; } append[k][j+1] = '