如题,输出1~n的全排列
1、分解:以1开头的全排列 + 以2开头的全排列 + …… +以n开头的全排列
不妨设一个数组P来存放当前的排列
2、解决每一个子问题
按顺序往P中填充数字,数字的范围是1~n。首先是要枚举。不妨假设填好了P[1] ~ P[index - 1], 正准备填P[index],如果要填入的数字k还没有在P[1]~P[index - 1]中出现过(即hashtable[k] = 0),就P[index] = k, hashtable[k] = 1(表示k已经出现过了),然后开始处理P[index + 1]。当index == n + 1时,代表这一填充的数字已经够了,已经构成了一个全排列,可以输出这个全排列了。
3、图解
4、代码(输出语句为理解逻辑的语句)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int P[20], hashtable[20];
int n;
void dfs(int index) {
if (index == n + 1) {
printf("递归边界,已经处理完排列的1~N位\n");
printf("输出当前排列:\n");
for (int i = 1; i < n; i++)
printf("%d ", P[i]);
printf("%d\n", P[n]);
return;
}
for (int x = 1; x <= n; x++) {
printf("枚举,试图把%d填入P[%d]\n", x, index);
if (hashtable[x] == 0) {
printf("如果%d不在P[0]到P[%d-1],令P[%d] = %d, 即把%d加入当前排列\n", x, index, index, x, x);
P[index] = x;
hashtable[x] = 1;
printf("%d已经在P中\n", x);
printf("处理排列的第%d + 1位\n", index);
dfs(index + 1);
printf("处理完P[%d]为%d的子问题,还原状态, hashtable[%d] = 0\n", index, x, x);
hashtable [x] = 0;
}
}
}
int main() {
scanf("%d", &n);
memset(P, 0, sizeof(P));
memset(hashtable, 0, sizeof(hashtable));
dfs(1);
return 0;
}
5、八皇后问题
核心点在于:两个皇后不能在同一行、同一列、同一条对角线。对于每列的皇后,他们的行号全部输出来,其实就是一个1~n的全排列(即i,j表示列号,P[i], P[j]表示行号)。由此,两个皇后一定是不在同行同列的,也就是说,当我们找到一个全排列(index == n+ 1)后,我们只需要遍历任意两个皇后,再判断他们在不在一条对角线上即可。于是判断条件为(abs(i - j) == abs(P[i] - P[j]))。直接在前面的全排列代码基础上修改即可。
值得一提的是,在运行时用于给可行方案计数的变量count出现了报错:变量不明确。这是由于namespace中的count命名导致的。于是改成了cnt
//暴力解法
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>
using namespace std;
int cnt = 0, n;
int P[20];
int hashtable[20] = { 0 };
void dfs(int index) {
if (index == n + 1) {
int flag = 1;
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (abs(i - j) == abs(P[i] - P[j])) flag = 0;
}
}
if (flag) cnt++;
return;
}
for (int x = 1; x <= n; x++) {
if (hashtable[x] == 0) {
P[index] = x;
hashtable[x] = 1;
dfs(index + 1);
hashtable[x] = 0;
}
}
}
int main() {
scanf("%d", &n);
memset(P, 0, sizeof(P));
dfs(1);
printf("%d", cnt);
return 0;
}