AcWing 842. 排列数字
原题链接
简单
作者:
Coding酥
,
2024-02-13 22:08:57
,
所有人可见
,
阅读 44
#include<iostream>
using namespace std;
const int N = 10;
int path[N]; // 暂存路径
bool st[N]; // 记录当前位置已经使用的数
int n;
void dfs(int u){
// 当u==n时已经递归遍历完所有位置
if(u == n) {
for(int i = 0; i < n; i++) cout << path[i] << " ";
cout << endl;
}
// 遍历当前位置没用过的每一个数
for(int i = 1; i <= n; i++){
if(!st[i]){ // 当前位置的这个数没用过
path[u] = i; // 给当前位置赋值
st[i] = true; // 记录已经用过的数
dfs(u+1); // 对下一个位置进行递归
st[i] = false; // 恢复状态
}
}
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin >> n;
// 从第0层开始递归
dfs(0);
return 0;
}