#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
#include <stack>
#include <iomanip>
using namespace std;
// vis数组 是visit 不是看
// dfs跟那个地图里面找相连,最终连成一片联通分量 这样来想。他就是递归。
int n;
int a[21]; //存放全排列
int vis[21]; // 1 - n : 是否使用过
void print() {
for (int i = 1; i <= n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
//step == 1 说明第一个位置 放的数字
void dfs(int step) {
if (step > n) {
print();
}
for (int i = 1; i <= n; i++){
if (vis[i] == 0){
a[step] = i;
vis[i] = 1;
dfs(step + 1);
vis[i] = 0;
}
}
}
int main() {
while(cin >> n) {
dfs(1);
};
}
有点难,回溯这个问题。背了吧
#include <iostream>
#include <queue>
using namespace std;
int ori[101] = {1,2,3,6,7,8};
int mark[101];
int res[101];
int maxIndex = 2;
void print() {
for (int i = 0; i <= maxIndex; i ++) {
cout << res[i] << " ";
}
cout << endl;
}
void dfs(int step) {
if (step > maxIndex) {
print();
return ;
}
for (int i = 0; i <= maxIndex; i++) {
if (mark[i] == 0) {
res[step] = ori[i];
mark[i] = 1;
dfs(step + 1);
mark[i] = 0;
}
}
}
int main() {
for (int i = 0; i <= 100; i++) {
mark[i] = 0;
}
dfs(0);
}