2014-09-06 73 views
2

我想要获得与输入arrayList长度相同的ArrayList的所有可能的排列组合。即1,2,3的ArrayList将导致123,132,213,231,321,312,不包括诸如1,2,12,13等的较短排列。这是我迄今为止的代码:获取一个ArrayList的所有可能的排列的ArrayList

public void getAllPermutations(ArrayList<coordinate> coords) { 
     ArrayList<coordinate> sub = new ArrayList<coordinate>(); 
     permutateSub(sub, coords); 
    } 

    private ArrayList<ArrayList<coordinate>> permutateSub(ArrayList<coordinate> sub, 
      ArrayList<coordinate> coords) { 
     int n = coords.size(); 
     if(n == 0) System.out.println(sub); 
     else { 
      if(sub.size()==n) { 
      System.out.println(sub); 
      for(int i = 0; i<n; i++) { 
       ArrayList<coordinate> a = new ArrayList<coordinate>(sub); 
       a.add(coords.get(i)); 
       ArrayList<coordinate> b = new ArrayList<coordinate>(coords); 
       b.remove(i); 
       permutateSub(a, b); 
      } 
     } 

    } 

坐标是一个类,只有x,y,并被访问以保存项目的2D点。

当前我正在使用此代码将其打印到控制台,但我也希望如果有人能够阐明我如何将它存储到ArrayList>中。谢谢。

+0

看起来这可能是http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string – mkobit 2014-09-06 21:10:03

+0

有趣的副本,我看到方法'permutateSub'的声明就好像它应该返回一个'ArrayList >'对象,但是我在函数的代码中没有看到'return'。 – 2014-09-06 21:20:05

+0

糟糕,我的错误。无论如何,它仍然会返回更短的排列。 – AHalbert 2014-09-06 21:26:34

回答

3

下面是做这件事:

public static void permutation(List<coordinate> nums) { 
    List<List<coordinate>> accum = new ArrayList<List<coordinate>>(); 
    permutation(accum, Arrays.<coordinate>asList(), nums); 
    System.out.println(accum); 
} 

private static void permutation(List<List<coordinate>> accum, List<coordinate> prefix, List<coordinate> nums) { 
    int n = nums.size(); 
    if (n == 0) { 
     accum.add(prefix); 
    } else { 
     for (int i = 0; i < n; ++i) { 
      List<coordinate> newPrefix = new ArrayList<coordinate>(); 
      newPrefix.addAll(prefix); 
      newPrefix.add(nums.get(i)); 
      List<coordinate> numsLeft = new ArrayList<coordinate>(); 
      numsLeft.addAll(nums); 
      numsLeft.remove(i); 
      permutation(accum, newPrefix, numsLeft); 
     } 
    } 
} 
+0

只是提到它,这是使用Java 8的功能。 – 2014-09-06 21:24:16

+0

谢谢您的贡献!但是,它们不是整数列表,它们是坐标列表。所以会出现几个涉及List的错误。 – AHalbert 2014-09-06 21:25:11

+0

您可以用'坐标'搜索并替换'Integer' – janos 2014-09-06 21:29:21

4

看看番石榴的Collections2 permutations方法。

实施例(source

public void permutations() { 
    List<Integer> vals = Ints.asList(new int[] {1, 2, 3}); 

    Collection<List<Integer>> orderPerm = Collections2.permutations(vals); 

    for (List<Integer> val : orderPerm) { 
     logger.info(val); 
    } 
} 

/* output: 
[1, 2, 3] 
[1, 3, 2] 
[3, 1, 2] 
[3, 2, 1] 
[2, 3, 1] 
[2, 1, 3] 
*/ 
+1

+1:无需重新发明轮子。无论如何,番石榴在许多情况下都会有所帮助。 – 2014-09-06 21:40:50

+0

未来,我一定会利用这个。非常感谢。 – AHalbert 2014-09-06 22:12:39

相关问题