递归实现排列型枚举

 

 方法一:c++自带的next_permutation函数

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int a[15];
 4 int main() {
 5     int n;
 6     cin >> n;
 7     for (int i = 0; i < n; i++) {
 8         a[i] = i + 1;
 9     }
10     sort(a, a + n);
11     do {
12         for (int i = 0; i < n; i++) {
13             cout << a[i] << " ";
14         }
15         cout << endl;
16     } while(next_permutation(a, a + n));
17     return 0;
18 }

方法二:dfs。搜索顺序:从前往后遍历每个位置,判断这个位置放哪个数

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 15;
 4 int way[N]; //存储每种方案
 5 bool used[N]; //判断每个数有没有被用过,true表示用过,false没用过
 6 int n;
 7 void dfs(int u) {
 8     if (u == n + 1) {
 9         for (int i = 1; i <= n; i++) { //打印方案
10             cout << way[i] << " ";
11         }
12         cout << endl;
13         return;
14     }
15     //依次枚举每个分支,即当前位置可以放哪些数
16      for (int i = 1; i <= n; i++) { //从小到大
17          if (!used[i]) { //找一个没用过的数
18             way[u] = i; //放在u这个位置
19             used[i] = true; //i这个数用过了
20             dfs(u + 1); //搜索下一层
21             way[u] = 0; //回溯回复现场
22             used[i] = false;
23          }
24      }
25 }
26 int main() {
27     cin >> n;
28     dfs(1); //从第一位开始
29     return 0;
30 }
原文地址:https://www.cnblogs.com/fx1998/p/13901431.html