[递归] 全排列-C语言
使用此方法很容易能理解该递归算法
#include<stdio.h>
#include<string.h>
void swap(char *a, char *b) {
char tmp;
tmp = *a;
*a = *b;
*b= tmp;
}
void permutation(char* str,int sbegin,int send) //全排列的非去重递归算法
{
int i;
if(sbegin == send) //当 sbegin = send时输出
{
for( i = 0; i<=send; i++) //输出一个排列
printf("%c", str[i]);
printf("\n");
}
else
{
for( i = sbegin; i <= send; i++) //循环实现交换和sbegin + 1之后的全排列
{
swap(&str[i], &str[sbegin]); //把第i个和第sbegin进行交换
permutation(str, sbegin + 1, send);
swap(&str[i], &str[sbegin]); //【注1】交换回来
}
}
}
int main() {
char tmp[50];
scanf("%s", tmp);
printf("全排列:\n");
permutation(tmp, 0, strlen(tmp)-1);
}