java全排列通用工具類
全排列處理接口
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
本文由用戶 felixilef 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!