import java.util.ArrayList; public class { public static ArrayList<int[]> permutation(int[] arr){ ArrayList<int[]> res = new ArrayList<int[]>(); if(arr == null || arr.length==0) return null; perm(res, 0, arr); return res; } public static void perm(ArrayList<int[]> res, int i, int[] arr){ if(i==arr.length-1){ res.add(arr.clone()); }else{ for(int j=i; j<arr.length; ++j){ swap(arr, i, j); perm(res, i+1, arr); swap(arr, i, j); } } } public static void swap(int[] str, int i, int j) { if (i != j) { int t = str[i]; str[i] = str[j]; str[j] = t; } } public static void main(String[] args) { int[] arr = {1,2,3,4}; int[] tmp; ArrayList<int[]> res; res = permutation(arr); for(int i=0; i<res.size(); ++i){ tmp = res.get(i); for(int j=0; j<tmp.length; ++j) System.out.print(tmp[j]+" "); System.out.println(); } System.out.println(res.size()); } }
|