fork(1) download
  1. import java.util.*;
  2. import java.lang.*;
  3.  
  4. class Main
  5. {
  6. public static void main (String[] args) throws java.lang.Exception
  7. {
  8. List<Character> list = new ArrayList<Character>();
  9. list.add('1');
  10. list.add('2');
  11. list.add('3');
  12. list.add('4');
  13. list.add('5');
  14. list.add('6');
  15.  
  16. System.out.println( combinations( list,2 ).toString() );
  17. }
  18.  
  19. static <T> List<List<T>> combinations( List<T> list, int n ){
  20.  
  21. List<List<T>> result;
  22.  
  23. if( list.size() <= n ){
  24.  
  25. result = new ArrayList<List<T>>();
  26. result.add( new ArrayList<T>(list) );
  27.  
  28. }else if( n <= 0 ){
  29.  
  30. result = new ArrayList<List<T>>();
  31. result.add( new ArrayList<T>() );
  32.  
  33. }else{
  34.  
  35. List<T> sublist = list.subList( 1, list.size() );
  36.  
  37. result = combinations( sublist, n );
  38.  
  39. for( List<T> alist : combinations( sublist, n-1 ) ){
  40. List<T> thelist = new ArrayList<T>( alist );
  41. thelist.add( list.get(0) );
  42. result.add( thelist );
  43. }
  44. }
  45.  
  46. return result;
  47. }
  48.  
  49. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
[[5, 6], [6, 4], [5, 4], [6, 3], [5, 3], [4, 3], [6, 2], [5, 2], [4, 2], [3, 2], [6, 1], [5, 1], [4, 1], [3, 1], [2, 1]]