c++ dfs求解出字母的排列


前言

前面咱们学习过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函数。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值