java实现排座位

** 排座位**

要安排:3个A国人,3个B国人,3个C国人坐成一排。
要求不能使连续的3个人是同一个国籍。
求所有不同方案的总数?

参考答案:
283824

public class Main1 {
    
    public static int count = 0;
    
    public void swap(int[] A, int a, int b) {
        int temp = A[a];
        A[a] = A[b];
        A[b] = temp;
    }
    
    public void dfs(int[] A, int step) {
        if(step == A.length) {
            if(check(A))
                count++;
            return;
        } else {
            for(int i = step;i < A.length;i++) {
                swap(A, i, step);
                dfs(A, step + 1);
                swap(A, i, step);
            }
        }
        return;
    }
    
    public boolean check(int[] A) {
        for(int i = 2;i < A.length;i++) {
            if(A[i] == A[i - 1] && A[i] == A[i - 2])
                return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        Main1 test = new Main1();
        int[] A = {1,1,1,2,2,2,3,3,3};
        test.dfs(A, 0);
        System.out.println(count);
    }
}
原文地址:https://www.cnblogs.com/a1439775520/p/13077057.html