使用此方法很容易能理解该递归算法
#include<stdio.h>#include<string.h>void swap(char *a, char *b) {char tmp;tmp = *a;*a = *b;*b= tmp;}// 对str[]中sbegin-send范围内的元素进行全排列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{// str[sbegin]位置有可能是sbegin-send中的任意元素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);}
