fork download
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Collections;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.Scanner;
  7. import java.io.*;
  8.  
  9. public class Main {
  10. static int arr[];
  11. static int result[];
  12. static int N;
  13. static int M;
  14. static boolean visited[];
  15. static BufferedWriter bw;
  16. static HashSet<String> set = new HashSet();
  17.  
  18. public static void main(String[] args) throws IOException {
  19. // TODO Auto-generated method stub
  20. Scanner sc = new Scanner(System.in);
  21. N = sc.nextInt();
  22. M = sc.nextInt();
  23. arr = new int[N];
  24. result = new int[M];
  25.  
  26. visited = new boolean[N];
  27.  
  28. for (int i = 0; i < N; i++) {
  29.  
  30. arr[i] = sc.nextInt();
  31.  
  32. }
  33.  
  34. Arrays.sort(arr);
  35. backtraking(0);
  36.  
  37. ArrayList list = new ArrayList(set);
  38. Collections.sort(list);
  39. Iterator it = list.iterator();
  40. while (it.hasNext()) {
  41. System.out.println(it.next());
  42. }
  43.  
  44. }
  45.  
  46. public static void backtraking(int index) throws IOException {
  47. if (index == M) {
  48. String a = "";
  49. for (int i = 0; i < M; i++) {
  50.  
  51. a += String.valueOf(result[i]) + " ";
  52.  
  53. }
  54. set.add(a);
  55.  
  56. return;
  57. }
  58. for (int i = 0; i < N; i++) {
  59.  
  60. if (visited[i])
  61. continue;
  62. visited[i] = true;
  63. result[index] = arr[i];
  64.  
  65. backtraking(index + 1);
  66. visited[i] = false;
  67.  
  68. }
  69. }
  70.  
  71. }
  72.  
  73.  
Success #stdin #stdout 0.06s 2184192KB
stdin
2 2
9 10
stdout
10 9 
9 10