算法描述:
R = {r1, r2, ..., rn}是要进行排列的n个元素,Ri = R-{ri}.
n == 1: perm(R) = (r),其中r是集合R中的唯一元素;
n > 1 : perm(R)由(r1)perm(R1),(r2)perm(R2),...,(rn)perm(Rn)构成。
代码:
#include <stdio.h>
#include <string.h>
#define MAX 100
int len, sum;
static int perm(char list[], int k, int m);
static int swap(char list[], int i, int j);
int main(int argc, char **argv)
{
char list[MAX];
fgets(list, sizeof(list), stdin);
len = strlen(list);
printf("Print result:\n");
sum = perm(list, 0, len-2);//not include '\n'
printf("sum = %d\n", sum);
return(0);
}
static int perm(char list[], int k, int m)
{
int i;
if(k == len-2){
for(i = 0; i<= m; i++){
printf("%c", list[i]);
}
sum++;
printf("\n");
}
for(i = k; i <= m; i++){
swap(list, k, i);
perm(list, k+1, m);
swap(list, k, i);
}
return sum;
}
static int swap(char list[], int i, int j)
{
char temp;
temp = list[i];
list[i] = list[j];
list[j] = temp;
return 0;
}
[xxxx@localhost sousuo]$ ./a.out 123 Print result: 123 132 213 231 321 312 sum = 6
|
阅读(917) | 评论(0) | 转发(0) |