1、思想

2、例题
给定一个整数 n,将数字 1∼n 排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
3、代码
本题dfs的是位置 即 第一个位置可以放什么元素 然后第二个元素可以填什么元素……………………….
而不是dfs整数1-n,此时不好考虑。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#define PI 3.14159
using namespace std;
typedef pair<int,int> PII;
typedef long long LL;
const int MAX_INT = 0x3f3f3f3f;
const int N = 1e5+15;
const int mod = 1e9+7;
-------------------------------------------------------------------
int flag[N];//标记元素是否访问过
int path[N];//记录序列
int n;
//dfs查找的是第u个位置
void dfs(int u)
{
if(u>n)
{
for(int i=1;i<=n;i++)//数字填完了,输出
{
cout<<path[i]<<" ";
}
cout<<endl;
}
for(int i=1;i<=n;i++)//找下一个未被访问的元素
{
if(flag[i]==0)//如果数字 i 没有被用过
{
path[u] = i;//放入空位
flag[i]=1;
dfs(u+1);//找第u+1的位置上应该放的元素
flag[i] = 0;//回溯 释放此处的元素
}
}
}
----------------------------------------------------------------
int main()
{
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin>>n;
dfs(1);
}