给定一个整数 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
dfs 递归注意
1.判重
2.恢复现场
#include<iostream>
using namespace std;
int n;
bool st[10];
void get(int x,string ans)
{
if(x>n)
{
for(int i=0;i<ans.size();++i)
{
cout<<ans[i]<<' ';
}
cout<<endl;
return;
}
for(int i=1;i<=n;++i)
if(!st[i])
{
st[i] = 1;
string temp = ans;
temp+='0'+i;
get(x+1,temp);
st[i] = 0;
}
}
int main()
{
cin>>n;
get(1,"");
}
排列数字 基础(dfs)
最新推荐文章于 2022-12-20 21:46:46 发布