问题描述:
字符串:ABC,它的全排列有六个
代码:
#include
#include
#define SWAP(a,b,t) ((t)=(a),(a)=(b),(b)=(t))
void permutation(char *ch, int min, int max) //min和max确定了需要排序的元素区间 min-max
{
int i;
char temp;
if (min == max)
{
printf("%s\n", ch);
count++;
}
else
{
for (i = min; i<= max; i++)
{
SWAP(ch[i], ch[min], temp);
permutation(ch, min+1, max);
SWAP(ch[i], ch[min], temp);
}
}
}
void main()
{
char p[] = {"abc"};
permutation(p, 0, sizeof(p)-1 - 1);
printf("count=%d\n", count);
system("pause");
}
结果如下:
然后,完成这一步之后,我分析了递归结束的条件,能不能通过改变递归条件,来达到,输出任意个数(不超过最大个数)元素排列的所有可能。
最终,我给出的代码为:
#include
#include
#define SWAP(a,b,t) ((t)=(a),(a)=(b),(b)=(t))
int count=0;
int num=2; //由于c语言没有引用,我也不想使用指针,所以就定义了全局变量。它的作用是需要给多少个元素进行排列
void permutation1(char *ch, int min, int max,int n)
{
int i;
char temp;
if (n==0) //递归条件的改变。
{
for (i = 0; i < num; i++)
printf("%c", ch[i]);
printf("\n");
count++;
}
else
{
for (i = min; i <= max; i++)
{
SWAP(ch[i], ch[min], temp);
permutation1(ch, min + 1, max,n-1); //每次给n-1,和上一个代码的不同点
SWAP(ch[i], ch[min], temp);
}
}
}
void main()
{
char p[] = {"abc"};
permutation1(p, 0, sizeof(p)-1-1,num);
printf("count=%d\n", count);
system("pause");
}
结果: