当前位置:网站首页>排列数字(DAY90)dfs
排列数字(DAY90)dfs
2022-07-30 05:26:00 【张学恒】
1:题目
dfs bfs 的区别
dfs 空间复杂度O(n) 数据结构 stack 栈 不具有最短性
bfs 空间复杂度O(2^n) 数据结构 queue 队列 可以搜到最短路(当权重为1时)
给定一个整数 n,将数字 1∼n 排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
输入格式
共一行,包含一个整数 n。
输出格式
按字典序输出所有排列方案,每个方案占一行。
数据范围
1≤n≤7
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
2:代码实现
#include<iostream>
using namespace std;
const int N=10;
int n;
int path[N];
bool st[N];
void dfs(int u)
{
if(u==n)
{
for(int i=0;i<n;i++)printf("%d ",path[i]);
puts("");
return;
}
else
{
for(int i=1;i<=n;i++)
if(!st[i])
{
path[u]=i;
st[i]=true;
dfs(u+1);
st[i]=false;
}
}
}
int main()
{
cin >> n;
dfs(0);
return 0;
}
边栏推荐
猜你喜欢

Programmers make money and practice, teach you how to do paid courses, self-media, paid articles and paid technical courses to make money

pytorch官网中如何选择以及后面的安装和pycharm测试步骤

The use of Conluce, an online document management system

JVM面试总结

go版本升级

It's time to have to learn English, give yourself multiple paths

力扣1047-删除字符串中的所有相邻重复项——栈

idea设置自动带参数的方法注释(有效)

力扣344-反转字符串——双指针法

力扣20-有效的括号——栈实现
随机推荐
Concurrent Programming Review
【LeetCode】Day107-除自身以外数组的乘积
路径依赖:穷人很难逆袭突破的科学道理
Hexagon_V65_Programmers_Reference_Manual (14)
无代码开发平台子管理员入门教程
Usage when saving pointers in std::vector
JVM 内存结构 超详细学习笔记(一)
[Redis Master Cultivation Road] Jedis - the basic use of Jedis
75. 颜色分类
解读 Kylin 3.0.0 | 更敏捷、更高效的 OLAP 引擎
上交所行情文件解析之mktdt04
Golang——从入门到放弃
容器化 | 在 KubeSphere 中部署 MySQL 集群
22-07-29 西安 分布式事务、Seata
MySQL(4)
Unity stepping on the pit record - the use of GetComponent
从字节码角度带你彻底理解i++与++i
容器化 | 构建 RadonDB MySQL 集群监控平台
力扣05-替换空格——字符串问题
力扣541-反转字符串2——双指针法