fork(18) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int[] a = {1,2,3,4};
  13. ArrayList<int[]> list = permutations(a);
  14. for(int[] s : list){
  15. for(int i : s){
  16. System.out.print(i);}
  17. System.out.println();}
  18. }
  19.  
  20. static ArrayList<int[]> permutations(int[] a) {
  21. ArrayList<int[]> ret = new ArrayList<int[]>();
  22. permutation(a, 0, ret);
  23. return ret;
  24. }
  25.  
  26. public static void permutation(int[] arr, int pos, ArrayList<int[]> list){
  27. if(arr.length - pos == 1)
  28. list.add(arr.clone());
  29. else
  30. for(int i = pos; i < arr.length; i++){
  31. swap(arr, pos, i);
  32. permutation(arr, pos+1, list);
  33. swap(arr, pos, i);
  34. }
  35. }
  36.  
  37. public static void swap(int[] arr, int pos1, int pos2){
  38. int h = arr[pos1];
  39. arr[pos1] = arr[pos2];
  40. arr[pos2] = h;
  41. }
  42. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
1234
1243
1324
1342
1432
1423
2134
2143
2314
2341
2431
2413
3214
3241
3124
3142
3412
3421
4231
4213
4321
4312
4132
4123