这道题是很典型的回溯算法题,卡了我两天,最后发现自己在sizeof认识上有误区,我把我的误区分享给大家。
char *s = "hello";
char s1[] = "hello";
int a, b;
a = sizeof(s);//a=4
b = sizeof(s1);//b=6
char str[2][6] = { "hello","hello" };
char **str1 = malloc(sizeof(char*) * 2);
str1[0] = malloc(sizeof(char) * 6);
str1[0] = "hello";
str1[1] = malloc(sizeof(char) * 6);
str1[1] = "hello";
a = sizeof(str[0]);a=6
b = sizeof(str1[0]);b=4
这些细微的差别希望大家能认识到
附上解题代码
int isPalin(char *s,int i){
int start=0;
int end=i;
while(start<end){
if(s[start++]!=s[end--])
return 0;
}
return 1;
}
void dfs(char *s,char **cur,char ***ret,int k,int *returnSize,int *col){
if(*s==0){
ret[*returnSize]=malloc(sizeof(char*)*k);
for(int i=0;i<k;i++){
ret[*returnSize][i]=malloc(sizeof(char)*(strlen(cur[i])+1));
strcpy(ret[*returnSize][i],cur[i]);
}
col[*returnSize]=k;
(*returnSize)++;
return;
}
for(int j=0;j<strlen(s);j++)
if(isPalin(s,j)){
memcpy(cur[k],s,j+1);
cur[k][j+1]='\0';
dfs(s+j+1,cur,ret,k+1,returnSize,col);
}
}
char *** partition(char * s, int* returnSize, int** returnColumnSizes){
*returnSize=0;
char ***ret=malloc(sizeof(char**)*500);//一个三维数组,包含了500个二维数组,并未指明二维数组大小
char **cur=malloc(sizeof(char*)*500);//一个二维数组,包含了500个一维数组,并未指明一维数组大小
int len=strlen(s);//len=9
int *col=malloc(sizeof(int)*(500));
for(int i=0;i<500;i++){
cur[i]=malloc(sizeof(char)*(len+1));
}
dfs(s,cur,ret,0,returnSize,col);
*returnColumnSizes=col;
return ret;
}