图书排列

将编号为1~10的10本书排放在书架上,要求编号相邻的书不能放在相邻的位置。
请计算一共有多少种不同的排列方案。

注意,需要提交的是一个整数,不要填写任何多余的内容。

答案:

代码:

#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
bool vis[11];
int c;
void dfs(int k,int last) {
    if(k >= 10) {
        c ++;
        return;
    }
    for(int i = 1;i <= 10;i ++) {
        if(vis[i] || abs(i - last) == 1) continue;
        vis[i] = true;
        dfs(k + 1,i);
        vis[i] = false;
    }
}
int main() {
    dfs(0,-1);
    printf("%d",c);
    return 0;
}
原文地址:https://www.cnblogs.com/8023spz/p/10730384.html