Method One: complex problem into smaller problems:
The first step: to do everything possible in the first place character.
Step two: a fixed first character, seeking arrange all of the following character.
#include<stdio.h>
#include<string.h>
void swap(char *a,char *b)
{
char temp;
temp=*a;
*a=*b;
*b=temp;
}
void solution(char *str,int start)
{
if(str[start]=='\0')
{
printf("%s\n",str);
return;
}
for(int i=start;str[i]!='\0';i++)
{
swap(&str[start],&str[i]);
solution(str,start+1);
swap(&str[start],&str[i]);
}
}
int main()
{
char str[10];
scanf("%s",str);
solution(str,0);
}
Method two: full permutation problem for the input string, using the depth search method.
Procedures are as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int book[10]={0};//标记排列中已有的数字
char array[10];//排列
int count=0;
//函数dfs
void dfs(char str[],int step,int length)
{
if(step==length+1){
for(int i=0;i<length;i++)
printf("%c",array[i]);
count++;
printf("\n");
return;
}
for(int i=0;i<length;i++){
if(book[i]==0){
array[step-1]=str[i];
book[i]=1;
dfs(str,step+1,length);
book[i]=0;
}
}
return;
}
int main()
{
char str[10];
int length;
memset(book,0,sizeof(book));
scanf("%s",str);
length=strlen(str);
printf("全排列如下:\n");
dfs(str,1,length);
printf("组合数总计:%d\n",count);
return 0;
}
Explained as follows: