填入0~9的数字。要求:连续的两个数字不能相邻。
(左右、上下、对角都算相邻)
一共有多少种可能填写的方案?
请填写表示方案数目的整数~
分析:从左到右从上到下标为0~9,将a[10]中的数字依次填入,所以只要将a数组从0123456789一直全排列试到9876543210,测试每一个结果是否满足,满足条件的次数累加得到的就是方案数目~答案是1580~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <algorithm> using namespace std; int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; bool judge(int i, int j) { return (a[i] - a[j] == 1 || a[i] - a[j] == -1); } bool func() { if (judge(0, 1) || judge(0, 3) ||judge(0, 4) ||judge(0, 5) ||judge(1, 2)||judge(1, 4) ||judge(1, 5) ||judge(1,6) ||judge(2, 5) ||judge(2, 6) ||judge(3, 4) ||judge(3, 7) ||judge(3, 8) || judge(4, 5) ||judge(4, 7) || judge(4, 8) ||judge(4, 9) ||judge(5, 6) ||judge(5, 8) || judge(5, 9) || judge(6, 9)|| judge(7, 8) ||judge(8, 9)) return false; return true; } int main() { int n = 1, cnt = 0; for (int i = 1; i <= 10; i++) n = n * i; for (int i = 1; i < n; i++) { next_permutation(a, a+10); if (func() == true) cnt++; } cout << cnt; return 0; } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼