前言
前面咱们学习过dfs求数字的排列,但是没有一起学习过dfs求出字母的排列,这篇文章将带简单给大家介绍一下字母的全排列
一、题意
例如
输入数据
3
abc
输出数据
a b c
a c b
b a c
b c a
c a b
c b a
二、代码
1.代码实现题意
代码如下(示例):
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
2.读入数据
代码如下(示例):
//输出abc的全排列
#include<bits/stdc++.h>
using namespace std;
int n;//定义数据的规模
char ans[10];//定义一个字符数组用于存入数组
int vis[10];//定义一个状态数组来表示元素的使用情况
char bns[10];//主函数里面输入的数组,用来给ans进行赋值
void dfs(int step)
{
if(step==n+1)//当step==n+1的时候输出
{
for(int i=1;i<=n;i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
return;
}
for(int i=1;i<=n;i++)
if(vis[i]==0)//如果该数据未被使用过
{
vis[i]=1;
ans[step]=bns[i];
dfs(step+1);//dfs
vis[i]=0;//回溯
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>bns[i];//输入bns的数据
dfs(1);
return 0;
}
运行结果
3//数据规模
abc//输入字符数组的内容bns
a b c
a c b
b a c
b c a
c a b
c b a
用dfs实现
三、总结
字母的排列和前面数字的排列大同小异,仅仅是多了一个给ans赋值的bns函数。