#dfs之全排列
题目传送门/全排列
给定一个由不同的小写字母组成的字符串,输出这个字符串的所有全排列。 我们假设对于小写字母有’a’ < ‘b’ < … < ‘y’ < ‘z’,而且给定的字符串中的字母已经按照从小到大的顺序排列。
Input
输入只有一行,是一个由不同的小写字母组成的字符串,已知字符串的长度在1到6之间。
Output
输出这个字符串的所有排列方式,每行一个排列。要求字母序比较小的排列在前面。
Sample Input
abc
Sample Output
abc
acb
bac
bca
cab
cba
对于这个题,emmm,dfs板子题。就是枚举它的每一种情况,把答案存数组,再输出就行了。下面来看代码。
#include<iostream>
#include<queue>
#include<string.h>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e5+5;
char temp[N];//答案数组
char ch[N];//原数组
int flag[N];//标记数组
void dfs(int cnt,int n)
{
if(cnt==n)//当位置达到原字符串的长度,即已经完成一次排序。
{
cout<<temp<<endl;
return ;
}
else
{
for(int i=0;i<n;i++)
{
if(!flag[i])
{
temp[cnt]=ch[i];//存答案
cnt++;
flag[i]=1;
dfs(cnt,n);
flag[i]=0;
cnt--;
}
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>ch;
int n=strlen(ch);
dfs(0,n);
}