例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()()()", "()(())"
数据范围:
要求:空间复杂度
,时间复杂度 )
int cmp(const void *a, const void *b) {
int i=0;
while(i<strlen(*(char**)a)) {
if((*(char**)a)[i] > (*(char**)b)[i])
return 1;
else if((*(char**)a)[i] < (*(char**)b)[i])
return -1;
else
i++;
}
return 0;
}
char** generateParenthesis(int n, int* returnSize ) {
char **proRes, **res, **lastres;
int lastreturnSize, proResreturnSize;
int i, j;
proRes = (char**)malloc(pow(2,14));
for(i=0; i<pow(2,14); i++)
proRes[i] = (char*)malloc(n*2+1);
if(n==0)
*returnSize = 0;
strcpy(proRes[0], "()");
*returnSize = 1;
if(n==1)
return proRes;
lastres = generateParenthesis(n-1, &lastreturnSize);
for(i=0, proResreturnSize=0; i<lastreturnSize; i++) {
for(j=0; j<strlen(lastres[i])+1; j++) {
if(j==0) {
strcpy(proRes[proResreturnSize], "()");
strcat(proRes[proResreturnSize++], lastres[i]);
}
else if(lastres[i][j-1]=='(' && lastres[i][j]==')') {
strncpy(proRes[proResreturnSize], lastres[i], j);
proRes[proResreturnSize][j] = 0;
strcat(proRes[proResreturnSize], "()");
strcat(proRes[proResreturnSize++], lastres[i]+j);
}
else if(lastres[i][j-1]==')' && lastres[i][j]=='(' && strncmp(lastres[i]+j-2, "()", 2)!=0) {
strncpy(proRes[proResreturnSize], lastres[i], j);
proRes[proResreturnSize][j] = 0;
strcat(proRes[proResreturnSize], "()");
strcat(proRes[proResreturnSize++], lastres[i]+j);
}
else if(lastres[i][j-1]=='(' && lastres[i][j]=='(') {
{
int m=0,n=0;
strncpy(proRes[proResreturnSize], lastres[i], j);
proRes[proResreturnSize][j] = 0;
strcat(proRes[proResreturnSize], "(");
while (1) {
if(lastres[i][j+n]=='(') {
m++;
n++;
strcat(proRes[proResreturnSize], "(");
}
else if(lastres[i][j+n]==')') {
m--;
n++;
strcat(proRes[proResreturnSize], ")");
}
else
break;
if(m==0)
break;
}
strcat(proRes[proResreturnSize], ")");
strcat(proRes[proResreturnSize++], lastres[i]+j+n);
}
if(strncmp(lastres[i]+j-2, "()", 2)!=0) {
strncpy(proRes[proResreturnSize], lastres[i], j);
proRes[proResreturnSize][j] = 0;
strcat(proRes[proResreturnSize], "()");
strcat(proRes[proResreturnSize++], lastres[i]+j);
}
}
}
}
qsort(proRes, proResreturnSize, sizeof(char*), cmp);
res = (char**)malloc(proResreturnSize*sizeof(char*));
res[0] = (char*)malloc(n*2+1);
strcpy(res[0], proRes[0]);
*returnSize=1;
for(i=1; i<proResreturnSize; i++) {
if(strcmp(res[*returnSize-1], proRes[i])!=0) {
res[*returnSize] = (char*)malloc((n*2+1));
strcpy(res[*returnSize], proRes[i]);
(*returnSize)++;
}
}
return res;
}