Problem P29. [算法课回溯]优美的排列
回溯加上满足优美的排列判断
#include<iostream>
#include<bits/stdc++.h>
#include<cstdio>
#include<string>
using namespace std;
int cnt;
void backTrack(vector<bool>& used, int idx, int n) {
if (idx > n) {
cnt++;
return;
}
for (int i = 1; i < n+1; i++) {
if (used[i] == true && (i%idx == 0 || idx%i == 0)) {
used[i] = false;
backTrack(used, idx+1, n);
// 回溯
used[i] = true;
}
}
}
int main()
{
int n;
cin >> n;
vector<bool> used = vector<bool>(n+1, true);
backTrack(used, 1, n);
cout << cnt;
return 0;
}