java全排列通用工具类

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

全排列处理接口    

public interface PermutationProcessor<T> {
    void process(T[]array);
}

全排列类    

public final class FullPermutation {

    public  static <T> void permutate(T a[], PermutationProcessor<T> processor) {
        permutate(a, 0, a.length,processor);

    }
   static <T>  void permutate(T a[], int m, int n,PermutationProcessor<T> processor) {
        int i;
        T t;
        if (m < n - 1) {
            permutate(a, m + 1, n,processor);
            for (i = m + 1; i < n; i++) {
                swap(a, m, i);
                permutate(a, m + 1, n,processor);
                swap(a, m, i);
            }
        } else {
            processor.process(a);
        }
    }

    private static <T> void swap(T[] a, int m, int i) {
        T t;
        t = a[m];
        a[m] = a[i];
        a[i] = t;
    }
}

[代码]调用示例    

    public static void main(String[] args) {
        Integer[] a={1,2,4};
        FullPermutation.permutate(a, new PermutationProcessor<Integer>() {
            @Override
            public void process(Integer[] array) {
                for(int i:array){
                    System.out.printf("%d ",i);
                }
                System.out.println();
            }
        });
    }

[代码]运行结果    

1 2 4 
1 4 2 
2 1 4 
2 4 1 
4 2 1 
4 1 2