【发布时间】:2025-12-04 22:35:02
【问题描述】:
我编写了一个程序,它接收一串字符,并打印出它们的所有可能组合。但是,有没有办法将每个组合记录在列表或数组中,而不仅仅是在屏幕上打印它们?因为我需要能够操纵一些连击,而不仅仅是看着它们。
void swap( char *a, char *b ){
char tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void permutation( char *c, int d, int e ){
int f;
if( d == e )
printf( "%s\n", c );
else{
for( f = d; f <= e; f++ ){
swap( ( c + d ), ( c + f ) );
permutation( c, d + 1, e );
swap( ( c + d ), ( c + f ) );
}
}
}
int main(){
char wordInput[25];
int len, arrLen, f;
printf( "\nEnter text: " );
gets( wordInput );
len = strlen( wordInput );
arrLen = len - 1;
permutation( wordInput, 0, arrLen );
return 0;
}
【问题讨论】:
-
提示:假设我们有一个单词是
k字母长,那么排列的数量将是k! = k(k-1)(k-2)...(3)(2)(1)所以你需要一个字符串数组(每个 k 字母长),它是大小!因此,首先使用 strlen 计算长度,然后使用 malloc 分配数组,然后使用您喜欢的任何内容(递归可以)运行排列以填充数组并瞧。尝试使用此提示创建程序。如果您遇到问题,将进一步提供帮助:-)
标签: c arrays printing permutation