1 #include<stdio.h> 2 /* 3 以ABCD为例: 4 1.固定A,递归求BCD的全排列,直到还剩一个字符,打印所有字符。恢复最初的排序。 5 2.A与B交换,固定B,递归求ACD的全排列。恢复最初的排序。 6 3.交换直到D的全排列求完为止。 7 */ 8 void perm(char str[], int k, int n){ 9 int i; 10 char temp; 11 if(k == n){ 12 for(i = 0; i < n; ++i) 13 printf("%c", str[i]); 14 printf("\n"); 15 }else{ 16 for(i = k; i < n; ++i){ 17 temp = str[k]; 18 str[k] = str[i]; 19 str[i] = temp; 20 perm(str, k+1, n); 21 temp = str[i]; 22 str[i] = str[k]; 23 str[k] = temp; 24 } 25 } 26 } 27 28 int main() 29 { 30 char str[5] = {"ABCD"}; 31 perm(str, 0, 4); 32 return 0; 33 }
【递归】递归算法求n个不同字符的全排序列
猜你喜欢
转载自www.cnblogs.com/chunlinn/p/11265634.html
今日推荐
周排行