我想列出n个数的所有排列到目前为止,一切似乎正常,但我遇到了一个非常奇怪的行为。使用此代码:
int **liste_permutations(int n){
int i, fact = factorielle(n);
int **tab=malloc(sizeof(int*)*fact);
for(i=0; i<fact; ++i)
{
tab[i] = malloc(sizeof(int)*n);
}
for(i=0;i<n;++i)
{
tab[0][i] = n-i;
}
for(i=1;i<fact;++i)
{
tab[i] = next_permutation(tab[i-1], n);
printf(" ");
}
return tab;}
此main()的输出
int **tab;
tab = liste_permutations(3);
for(i=0; i<factorielle(3); ++i)
{
for(j=0; j<3; ++j)
{
printf("%d", tab[i][j]);
}
printf("\n");
}
是
321
231
213
312
132
123
但如果我把它改成
int **liste_permutations(int n){
int i, fact = factorielle(n);
int **tab=malloc(sizeof(int*)*fact);
for(i=0; i<fact; ++i)
{
tab[i] = malloc(sizeof(int)*n);
}
for(i=0;i<n;++i)
{
tab[0][i] = n-i;
}
for(i=1;i<fact;++i)
{
tab[i] = next_permutation(tab[i-1], n);
}
return tab;}
主机的输出为:
321
231
321
231
321
231
例如,如果我尝试用n=5来做这个,输出是空的(可能是因为它尝试输出125“)
下面是下一个排列码:
int *next_permutation(int *t, int n){
//printf("n = %d\n", n);
int i, max, count;
for(i=0;(i<n) && (max !=i); ++i)
{
if(t[i] == n)
{
max = i;
}
if(t[i] == (t[i-1]+1))
{
++count;
if(count == (n-1))
{
return NULL;
}
}
}
//printf("max = %d\n", max);
if(n==1)
{
//printf("n=1\n");
return NULL;
}
int *next = malloc(n);
if(max == n-1)
{
//printf("max == n-1\n");
int *s;
s = malloc(sizeof(int));
for(i=0; i<(n-1);++i)
{
s[i]=t[i];
}
for(i=0; i<n-1; ++i)
{
//printf("%d", s[i]);
}
//printf("\n");
s = next_permutation(s, n-1);
if(s == NULL)
{
//printf("NUUUUUUl");
// next = NULL;
return NULL;
}
//printf("reprise en n = %d\n", n);
for(i=1;i<n;++i)
{
next[i] = s[i-1];
}
//printf("\n");
free(s);
next[0]=n;
return next;
}
else
{
//printf("max != n-1\n");
for(i=0; i<n; ++i)
{
next[i] = t[i];
}
int tmp = next[max];
next[max] = next[max+1];
next[max+1] = tmp;
for(i=0;i<n;++i)
{
//printf("%d", next[i]);
}
//printf("\n");
return next;
}}
编辑:修改了2的第一条评论,但我仍然有山姆的问题。
伊迪丝2:谢谢所有帮助我的人!特别是对mweerden,他给我指出了正确的道路(因为伯爵没有初始化)!
最佳答案
tab[i] = malloc(sizeof(int*)*n);
tab[i]
需要int
s的数组(而不是int*
s的数组)更改为
tab[i] = malloc(sizeof(int)*n);
阿尔索
int *s;
for(i=0; i<(n-1);++i)
{
s[i]=t[i];
}
不为
s
保留空间(未初始化使用)关于c - 没有printf,C for循环无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38931494/