/* * 输出n个元素的全排列 */ # include < stdio. h> void arrange( char * s, int k, int m) ; void swap ( char * s1, char * s2) ; int main( void ) { int n; int i; char * set ; printf ( "Please input the number of elements (>=0): " ) ; scanf ( "%d" , & n) ; if ( n < = 0) { printf ( "WARN! The number should be >= 1!/n" ) ; exit ( 0) ; } set = ( char * ) calloc ( n, sizeof ( char ) ) ; /* 分配存放集合元素的空间 */ if ( ! set ) { printf ( "Sorry! Not enough memory!/n" ) ; exit ( 0) ; }
/* 读取字符元素 , 限制了输入格式 */
printf ( "Please input the elements ('X X X ...'):/n/t" ) ; for ( i = 0; i < n; i+ + )
/* Notice the '%ls' : get the next non-blank character */
scanf ( "%ls" , & set [ i] ) ; printf ( "The set is: {" ) ; for ( i = 0; i < n - 1; i+ + ) printf ( "%c, " , set [ i] ) ; printf ( "%c}/n" , set [ i] ) ; printf ( "All arragnement is as follows:/n" ) ; arrange( set , 0, n- 1) ; free ( set ) ; getchar ( ) ; /* 防止输出窗口一闪关闭 */ getchar ( ) ; return 0; } void arrange( char * s, int k, int m) { int i; if ( k = = m) { printf ( "/t" ) ; for ( i = 0; i < = m; i+ + ) printf ( "%c" , s[ i] ) ; printf ( "/n" ) ; } else { for ( i = k; i < = m; i+ + ) { swap ( & s[ k] , & s[ i] ) ; arrange( s, k + 1, m) ; swap ( & s[ k] , & s[ i] ) ; } } } void swap ( char * s1, char * s2) { char temp = * s1; * s1 = * s2; * s2 = temp; }