先使用递归全排列,再判断,但是效率不高。代码如下:
package com.main; import java.util.Scanner; public class solution { public static int []num; public static int count=0; public static Boolean judge() { for (int i = 0; i < num.length; i++) { if (num[i] == i) { return false; } } for(int i=0;i<num.length-1;i++){ for(int j=1;i+j<num.length;j++){ if(num[i]==num[i+j]) return false; } } return true; } public static void setnum(int i) { if(i==num.length){ if(judge()){ count++; for(int k=0;k<num.length;k++) System.out.print((num[k]+1)+" "); System.out.println(); } }else{ for(int j=0;j<num.length;j++){ if(i==j){ continue; } num[i]=j; i++; setnum(i); i--; } } } public static void main(String[] args){ Scanner scanner=new Scanner(System.in); int n=scanner.nextInt(); while((n--)!=0){ count=0; int m=scanner.nextInt(); num=new int[m]; setnum(0); System.out.println(count); } } }