题目 思路 需要实现三个方法:检查是否编号相邻的书放在了相邻的位置的方法、元素交换位置的方法、排序的方法(调用元素交换位置的(swap())方法实现重新排序,再调用check方法判断新的排序是否符合条件)check(): 两个相邻的元素,如果它们的数字是相邻的,就是两个元素相减的绝对值 == 1,返回false即可swap(): 用位运算的方法,节省内存 Code package day1; public class Main { static int res=0; public static boolean check(int a[]) { int l=a.length; for(int i=0;i<l-1;i++) { // 两个相邻的元素,如果它们的数字是相邻的,就是两个元素相减的绝对值 == 1;那么就return false; if(Math.abs(a[i]-a[i+1])==1) { return false; } } return true; } // static int count=0; // 将a[]中的a[x] 与 a[y] 的值互换 public static void swap(int a[],int x,int y) { //位运算转换节省内存,如果x==y的话,无需转换 if(x==y) return; a[x]^=a[y]; a[y]^=a[x]; a[x]^=a[y]; // int temp =a[x]; // a[x]=a[y]; // a[y]=temp; } public static void dfs(int a[],int begin,int end) { if(begin==end) { // 检查相邻的书是否被放在了相邻的位置 :以数字来代表书;相邻两个数字的差的绝对值要不等于1 if(check(a)) // 如果相邻的两个数字的差的绝对值不等于1,则找到了一种方案。 res++; } for(int i = begin; i <= end; i++) { swap(a,begin,i); dfs(a,begin+1,end); swap(a,begin,i); } } public static void main(String[] args) { int a[]={1,2,3,4,5,6,7,8,9,10}; dfs(a,0,a.length-1); System.out.println(res); } }